Package and Interface
- Packages are containers for classes that are used to keep the class name space compartmentalized.
- For example, a package allows us to create a class named List, which you can store in your own package without concern that it will collide with some other class named List stored elsewhere.
- Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.
Defining a Package
To create a package is quite easy: simply include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name. (This is why you haven’t had to worry about packages before now.)
While the default package is fine for short, sample programs, it is inadequate for real applications. Most of the time, you will define a package for your code.
This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package called MyPackage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package MyPackage; package MyPack; class Balance { String name; double bal; Balance(String n, double b) { name = n; bal = b; } void show() { if(bal<0) System.out.print("--> "); JAVA LANGUAGE System.out.println(name + ": $" + bal); } } class AccountBalance { public static void main(String args[]) { Balance current[] = new Balance[3]; current[0] = new Balance("Sanjib", 123.23); current[1] = new Balance("Chandan", 157.02); current[2] = new Balance("Palak", -12.33); for(int i=0; i<3; i++) current[i].show(); } } |
Call this file AccountBalance.java, and put it in a directory called MyPack. Next, compile the file. Make sure that the resulting .class file is also in the MyPack directory. Then try executing the AccountBalance class, using the following command line:
java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this command, or to have your CLASSPATH environmental variable set appropriately. As explained, AccountBalance is now part of the package MyPack. This means that it cannot be executed by itself. That is, you cannot use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.
Importing Packages
Given that packages exist and are a good mechanism for compartmentalizing diverse classes from each other, it is easy to see why all of the built-in Java classes are stored in packages.
In a Java source file, import statements occur immediately following the package statement (if it exists) and before any class definitions. This is the general form of the import statement:
import pkg1 [.pkg2].(classname|*);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package MyPack; public class Balance { String name; double bal; public Balance(String n, double b) { name = n; bal = b; } public void show() { if(bal<0) System.out.print("--> "); System.out.println(name + ": $" + bal); } } |
As we can see, the Balance class is now public. Also, its constructor and its show( ) method are public,too. This means that they can be accessed by any type of code outside the MyPack package. For example, here TestBalance imports MyPack and is then able to make use of the Balance class:
1 2 3 4 5 6 7 8 9 |
import MyPack.*; class TestBalance { public static void main(String args[]) { Balance test = new Balance("J. J. Jaspers", 99.88); test.show(); // you may also call show() } } |
Interface
An interface is a collection of abstract methods (i.e. methods without having definition).
A class that implements an interface inherits abstract methods of the interface.
An interface is not a class.
Writing an interface is similar to writing a class, but they differ in concepts.
A class describes both attributes (i.e. variables) and behaviors (i.e. methods) of an object.
An interface contains only behaviors (i.e. methods) that a class implements.
If a class (provided it is not abstract) implements an interface, then all the methods of interface need to be defined in it.
Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to declare an interface:
1 2 3 4 5 |
public interface NameOfInterface { //Any number of final, static variables //Any number of abstract method declarations (i.e. method without definitions) } |
Interfaces have the following properties:
An interface is implicitly (i.e. by default) abstract. We do not need to use the abstract keyword when declaring an interface.
Each method in an interface is also implicitly (i.e. by default) abstract, so the abstract keyword is not needed.
Methods in an interface are implicitly (i.e. by default) public.
Implementing Interfaces
A class can implement more than one interface at a time.
A class can extend only one class, but can implement many interfaces.
An interface itself can extend another interface.
The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface…]]
{
// class-body
}
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
interface Message { void message1(); void message2(); } class A implements Message { void message1() { System.out.println("Good Morning"); void message2() { System.out.println("Good Evening"); } public static void main(String args[]) { A a=new A(); a.message1(); a.message2(); } <strong>}</strong> |
Similarities between class and interface
Both class and interface can contain any number of methods.
Both class and interface are written in a file with a .java extension, with the name of the
interface matching the name of the file.
The bytecode of both class and interface appears in a .class file.
Dissimilarities between class and interface
We cannot instantiate (i.e. create object) an interface but we can instantiate a class.
An interface does not contain any constructors but a class may contain any constructors.
All the methods in an interface are abstract (i.e. without definitions) but in a class method may or may not be abstract.
An interface cannot contain variables. The only variable that can appear in an interface must be declared both static and final. But a class can contain any variable.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces (i.e. multiple inheritances can be achieved through it). But a class can not extend multiple classes (i.e multiple inheritance can not be achieved).
Variables in Interfaces
We can use interfaces to import shared constants into multiple classes by simply declaring an interface that contains variables which are initialized to the desired values.
When we include that interface in a class (that is, when we “implement” the interface), all of those variable names will be in scope as constants. This is similar to using a header file in C/C++ to create a large number of #defined constants or const declarations.
If an interface contains no methods, then any class that includes such an interface doesn’t actually implement anything.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
interface SharedConstants { int X = 0; int Y = 1; } class A implements SharedConstants { static void show() { System.out.println(“X=”+x+”and Y=”+y); } public static void main(String args[]) { A a = new A(); show(); } } |
Interfaces Can Be Extended
One interface can inherit another by use of the keyword extends.
The syntax is the same as for inheriting classes.
When a class implements an interface that inherits another interface, it must provide
implementations for all methods defined within the interface inheritance chain.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
interface A { void meth1(); void meth2(); } interface B extends A { void meth3(); } class MyClass implements B { public void meth1() { System.out.println("Implement meth1()."); } public void meth2() { System.out.println("Implement meth2()."); } public void meth3() { System.out.println("Implement meth3()."); } } class IFExtend { public static void main(String arg[]) { MyClass ob = new MyClass();AVA LANGUAGE ob.meth1(); ob.meth2(); ob.meth3(); } } |
Assignments
Short Type Questions
1. Define package.
2. Define Interface.
3. Is the following interface valid?
4. Which package is always imported by default?
Long Type Questions
1. Discuss the difference between a class and an interface.
2. Differentiate between interface and abstract class.
3. Java supports multiple inheritances through interface. Discuss.
4. Explain the usage of Java packages.