Understanding Packages and Interfaces in Java
 
Published: 10 Aug 2007
Abstract
The article examines how to implement packages and interfaces in Java and the advantages and disadvantages with help from code samples.
by Debjani Mallick
Feedback
Average Rating: 
Views (Total / Last 10 Days): 60634/ 49

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



User Comments

Title: air max shoes r Five, please,��   
Name: anciag
Date: 2012-12-05 2:43:16 AM
Comment:
r Five, please,�� said the loud-speaker
Number Five was Roger Clint��s mount with the long white stockings. ��Do you [url=http://www.airmax2013cheap.com/nike-air-max-2011-c-5.html]air max 2011[/url] know what he calls it?�� Bee said. ��Operation Stockings.��
��It��s very ugly,�� Brat said. ��Looks as if he had walked through [url=http://www.airmax2013cheap.com/]nike new air max shoes[/url] air max 2013 a trough of whitewash.��
��He can jump, though.��
He could certainly jump, but he had phobia about water.
��Poor Roger,�� laughed Bee, watching Stockings refuse the water. ��He has been jumping him backwards and forwards across the duck pond at home in the hope of curing him, and now he does this!��
Stockings continued to refuse, and Clint had to take him out, in [url=http://www.airmax2013cheap.com/]new air max shoes[/url] a burst of sympathetic applause.
Numbers Six and Seven had one fault each.
Number Eight was Simon on Timber.
The black horse came into the ring exactly as he had come out of his box on the day Brat first saw him, pleased with himself and ready fo
Title: wholesale cheap ravens jerseys   
Name: ARMANI
Date: 2012-06-03 10:53:21 PM
Comment:
http://jerseymember.com/Baltimore-Ravens-Jerseys-s617.html
Title: 2012 NFL jerseys   
Name: NIKE NFL jerseys
Date: 2012-05-20 11:28:31 PM
Comment:
[/pre]Cheap NFL,NBA,MLB,NHL
[url=http://www.jersey2shop.com/]Jerseys From China[/url]
[url=http://www.jersey2shop.com/]2012 nike nfl Jerseys[/url]
[url=http://www.jersey2shop.com/]cheap China Jerseys[/url]
[url=http://www.jersey2shop.com/]Sports Jerseys China[/url]
[url=http://www.jersey2shop.com/NFL-Jerseys-c68/]NFL Jerseys China[/url]
[url=http://www.jersey2shop.com/NBA-Jerseys-c77/]NBA Jerseys China[/url]
NHL Jerseys China
[url=http://www.jersey2shop.com/MLB-Jerseys-c94/]MLB Jerseys China[/url]NFL jerseys For Sale online.All Our Jerseys Are Sewn On and Directly From Chinese Jerseys Factory
[/pre]
[pre]We Are Professional China jerseys Wholesaler
[url=http://www.cheapjersey2store.com/]Wholesale cheap jerseys[/url]Cheap mlb jerseys
[url= http://www.cheapjersey2store.com/]2012 mlb all atar jerseys[/url]
[url= http://www.cheapjersey2store.com/ [/url]Cheap China Wholesael[/url]
[url= http://www.cheapjersey2store.com/]Wholesale jerseys From China[/url]
[url=http://www.cheapjersey2store.com/]2012 nike nfl Jerseys[/url]Free Shipping,Cheap Price,7 Days Deliver
[/pre]
[/pre]
We are professional jerseys manufacturer from china,wholesal
sports [url= http://www.cheapjersey2store.com/]Jerseys From China[/url]
[url=http://www.cheapjersey2store.com/NFL-Jerseys-c68]NFL jerseys China[/url]
[url=http://www.cheapjersey2store.com/NHL-Jerseys-c96/]NHL Jerseys China[/url]
[url=http://www.cheapjersey2store.com/NBA-Jerseys-c77/]NBA Jerseys China[/url]
[url=http://www.cheapjersey2store.com/MLB-Jerseys-c94/]MLB Jerseys China[/url]
[url= http://www.cheapjersey2store.com/]China Jerseys[/url],Free Shipping
[/pre]
[/pre]
We are professional jerseys manufacturer from china,wholesal
sports [url= http://www.jerseycaptain.com/]cheap jerseys sale online [/url]
[url= http://www.jerseycaptain.com/]2012 nike nfl Jerseys[/url]
[url=http://www.jerseycaptain.com/NFL-Jerseys-c68]cheap NFL jerseys China[/url]
[url=http://www.jerseycaptain.com/NHL-Jerseys-c96/]NHL Jerseys C
Title: Real time example   
Name: Axe
Date: 2012-04-10 10:19:44 PM
Comment:
Any real time example for package which is used in daily life
Title: creating a package   
Name: golnaz
Date: 2012-01-23 4:01:45 AM
Comment:
Thanks a lot, was very useful
Title: Packages and interfaces   
Name: Lesedi
Date: 2011-02-25 5:55:35 AM
Comment:
post more details
Title: packages and interfaces in java   
Name: sinha timir krishna murari
Date: 2010-11-14 6:59:20 AM
Comment:
explanation of the concept in full detail with the definition of the topic
Title: drawback of interface   
Name: neeraj singh
Date: 2010-09-16 4:17:34 PM
Comment:
post in detail moreeeeeeeeeeee
Title: creating package   
Name: Nitesh
Date: 2010-04-20 12:53:18 AM
Comment:
gives alot of confidence to person
Title: thakur   
Name: Nitesh
Date: 2010-04-20 12:49:47 AM
Comment:
give more information
Title: package   
Name: puja
Date: 2010-01-27 11:05:13 AM
Comment:
can give more information about advantages of packages.
Title: Mistake   
Name: Gyandeep
Date: 2009-11-19 5:16:23 AM
Comment:
Ma'am, you have made a slight mistage here. The refernce variable you have used d takes r to its account and prints r.area(). It should be d.area. In the main().

Thanks and cheers!
Title: Interfaces and packages   
Name: Tamkeen
Date: 2009-07-07 2:55:10 AM
Comment:
Very precise and easily understandable language.
Title: package   
Name: Duraipandi
Date: 2008-10-14 7:34:39 AM
Comment:
It is very nice.here syntax and examples are each and every thing fine.
Title: very nice elaboration   
Name: Regalla Naresh Reddy
Date: 2008-06-10 3:36:05 AM
Comment:
Its vey nice.If you include syntax and an exmaple on syntax looks very nice.So try it
Title: doubt   
Name: raghavendra
Date: 2008-03-15 3:01:11 AM
Comment:
i have created a package named account and i created a new folder name test inside test i written a java program to access the package account.. its saying package account not found.. kindly help me.. if any..
Title: very nice   
Name: antony
Date: 2008-01-22 6:14:33 AM
Comment:
its very very useful for beginers.so thanks for you.and also i want more in swing and awt etc
Title: Nice   
Name: Ed
Date: 2007-08-12 10:34:37 PM
Comment:
NICE ARTICLE
Title: Good work   
Name: Rick
Date: 2007-08-10 10:50:14 PM
Comment:
It is a good piece of work.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-23 6:56:36 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search