AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1340&pId=-1
Understanding Packages and Interfaces in Java
page
by Debjani Mallick
Feedback
Average Rating: 
Views (Total / Last 10 Days): 75249/ 242

Introduction

Packages and interfaces form a very important concept in Java. In our day to day life, as a software developer, sometimes we need to handle small projects and at other times, big projects. In small projects, it is a normal practice to keep all the related files in a single directory. For example, all Java files use a single directory, all CSS files in some other directory, etc. But as the number of files increase when the project becomes big, it really becomes difficult to maintain all the files in the same directory. In Java this problem can be avoided by the use of packages.

Packages

Packages in Java are nothing more than a way to organize the files into different directories according to the functionality, category, etc. Just as files in one directory will have different functionality from those of another directory, files in one package will have a different functionality from the files in a different package. For example, files in java.io package contain functionality related to I/O, but the files in java.net package contain functionality related to a network. Package is a collection of classes that avoids name space collision. For example, if we have a class named “Vector” this name would clash with the “Vector” class present in JDK (Java Development Kit), but in real life this never happens as JDK “Vector” class is present in java.util package which is a separate package. So we can create a Vector class simply or we can put it in some other package, but we cannot create multiple classes having the same name in a single package. However, we can create a class hierarchy and keep them in a package. Packages can also be considered as a container for classes.

Creating a Package

The statement that is used to create a package requires a keyword called “package” and the following syntax.

Listing 1

package packagename;

The package definition must be the first statement of the java program file. Suppose we have a program file named “Firstapplication.java” and we want to put it inside a package called Example, then the coding that would go inside is:

Listing 2

package Example;
public class Firstapplication 
{
      public static void main(String a[ ]) 
      {
            System.out.println("This is my first application");
      }
}

If package statement is not specified, all the classes are stored in a default unnamed package.

Setting up the classpath

When we write a java program file having extension .java, it is kept under a particular directory. After compilation, the class file is created in the same directory. To execute the program we have to specify the class filename only. If a package is included then the name of the package must be a directory and after compiling the java file, the class files are stored under that package directory. To run a class of a particular package the following commands must be used.

Listing 3

java packagename.classname

However, this command must be given from the directory in which the package directory is present. For our Firstappplication example, if we are placing the Example package under C directory then we can set the classpath as:

Listing 4

set classpath = .;C:\;

The above statement sets the classpath to point at two places: .(dot) and C directory. Dot is used as an alias to represent the current directory. Semicolon is used to separate the directory location in case class files are placed at many locations.

As mentioned earlier, if we have placed our java file inside Example directory (which is placed inside C directory), for compiling we need to go to the Example directory and write the command as shown below.

Listing 5

C:\Example\javac Firstapplication.java

If we try to run the same by using java Firstapplication, then we get an error because the Firstapplication program is now a part of the package Example. For running the application we need to specify the fully qualified class name. Let us take another example; we have a package called Hello containing the file HelloWorld.java within Example package. Whenever we want to reference the HelloWorld class, we have to use Example.Hello.HelloWorld as its fully classified class name. For using the classes stored in a package, either we can declare the fully classified class name as shown:

Listing 6

//for first package 
Example.Firstapplication firstApplication = newExample.Firstapplication();
//for the subpackage 
Example.Hello.HelloWorld helloWorld = new Example.Hello.HelloWorld(); 

or we can use the import statement:

Listing 7

import.Example.*; //import all the public classes inside Example package
import.Example.Hello.*; //import all the public classes inside Hello package
import.Example.Firstapplication; //import only Firstapplication inside Example

By using the first import statement we can use the public classes present inside Example package but not the classes of Hello package.

Advantages of using Packages

·         Anyone can easily determine which files are related.

·         Name space collision is minimized.

·         One can allow types in one package to have unrestricted access to one another, still restricting the access for the types outside the package.

·         Java packages can be stored in compressed files called JAR files, thus allowing the classes to download faster as a group rather than downloading each one at a time.

Disadvantages of using Packages

·         We cannot pass parameters to packages.

·         Updating any one of the functions or procedures will invalidate other objects using different functions or procedures of the same package as the whole package is required to be compiled.

Basic Packages in Java

1.      java.io – input output operations

2.      java.lang – basic language functionalities

3.      java.math – arithmetic

4.      java.net – networking applications

5.      java.sql – database operations

6.      java.awt – user interfaces, painting graphics and images

Interfaces

Objects, through the methods they expose, define their interaction with the outside world. An interface is a collection of instance variables and instance methods without having any body, i.e., the methods do not have any definition. Once an interface is declared, any number of classes can implement that method. In other words, the classes contain all the members of the interface and they implement the definition of the method declared in the interface. By implementing an interface, we can achieve multiple and hierarchical inheritance as well as achieve dynamic (run time) polymorphism.

Declaring an Interface

The syntax for declaring an interface is:

Listing 8

Accessspecifier interface interfacename
{     
specifier datatype variable = value;
      …
      …
      specifier returntype methodname(parameter);
      …
      …
}

In the above example interface is a keyword.

Access specifiers – This must be public or it can be omitted as well. If the access specified is omitted, then the classes of the same package can only implement that interface in which the interface is present and if the access specified is public then classes of any package can implement the interface.

Implementing an Interface

The classes which implement an interface contain all the members of the interface as well as some of its own member. The syntax of implementing an interface is a shown below.

Listing 9

class classname implements interfacename
{
      own members;
      public void display()
      {
            ……
            ……
            ……
      }
}

Example of implementing Interface

The example below shows the implementation of an interface D2 having a function area.

Listing 10

interface D2
{
      public void area(int x,int y);
}
class triangle implements D2
{
      int base;
      int height;
      public void area(int x,int y)
      {
            int a;
            base = x;
            height = y;
            a = ½*base*height;
            System.out.println(“Area is:”+a);
      }
}
class rectangle implements D2
{
      int length;
      int breadth;
      public void area(int x,int y)
      {
            int a;
            length = x;
            breadth = y;
            a = length*breadth;
            System.out.println(“Area is:”+a);
      }
}
class result
{
public static void main(String a[ ])
{
      D2 d;
triangle t = new triangle();
      d = t;
      d.area(10,5);
      rectangle r = new rectangle();
      d = r;
      r,area(3,4);
}
}

Here the function area () of interface D2 is first implemented by the class triangle to calculate the area of a triangle and then it is implemented by another class named rectangle for calculating the area of a rectangle.

Inheritance in Interface

Look at the code sample given below.

Listing 11

interface a
{
      public void x();
      public void y();
}
interface b extends a
{     
      public void z();
}
class c implements a
{
      methods of a to be declared
}
class c implements b
{
      methods of a and b are to be declared
}

 

An interface can be derived from another interface. The syntax of inheriting an interface is the same as inheriting a class. When a class implements an interface, which is again inherited form another interface, in such cases the class must define all the methods of the base interface as well as the derived interface.

Advantages of Interface

·         Interfaces are mainly used to provide polymorphic behavior.

·         Interfaces function to break up the complex designs and clear the dependencies between objects.

Disadvantages of Interface

·         Java interfaces are slower and more limited than other ones.

·         The use of an interface which is not implemented more than once is just a waste of resources.

Conclusion

Using packages and interfaces in java certainly results in better organized code and functionality. It is a good coding practice to wrap codes using packages for organizing similar files in one place and to use interfaces wherever common functionality is required more than once.

By Debjani Mallick


Product Spotlight
Product Spotlight 

©Copyright 1998-2021 ASPAlliance.com  |  Page Processed at 2021-03-05 2:56:03 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search