0
5.3kviews
With proper example, explain steps to create a package and add a class or interface.

Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology

Marks: 5 M

Year: May 2014, Dec 2014, May 2015

1 Answer
0
66views
  • A package is called as the collection of classes and interfaces.
  • A Java package is simply a directory that contains one or more class files. It is, therefore, just a matter of:
  • Creating a folder
  • Moving the class file to the new folder (or creating them there)
  • Calling the package from any applications
  • The first step is to create the directory for the package. This can go in one of two places:
  • In the same folder as the application that will be using it
  • In a location listed in the system CLASSPATH environmental variable
  • So, for example, if CLASSPATH contains C:\Java\Packages then the new package can be created there, for example C:\Java\Packages\suite101, and once the directory has been created then classes can be added to it.
  • Next step is to create a class, Java source file. The first line of a class in a package is essential - it must contain the name of the package:

    package suite101;

  • No code is allowed above the package statement, but after that critical line the class can be defined as normal. For example it can call any packages that it requires:

    import java.util.* ;

    import java.text.* ;

  • In this example the class contains a single method which returns today's date formatted for the current locale:

    public class formatted_date 
    {
    public static String today ()
    {
    Date mydate = new Date();
    String dateString =DateFormat.getDateInstance().format(mydate);
    return dateString;
    }
    }
    
  • As always the code must be saved to a text file with the same name as the class - in this case that's C:\Java\Packages\suite101\formatted_date.java.

  • Now, we can use the above created java package in any program by import statement:

    import suite101.* ;

  • This will load any classes found in the suite101 directory. The formatted_date class can now be used in the class for the new application.

     public class use_packages 
     {
     public static void main(String args[])
     {
    formatted_date newday = new formatted_date();
    System.out.println(newday.today());
    }
    }
    
  • The above code makes use of formatted_date class by importing suite101 package.

Please log in to add an answer.