Unit IV Packages&Interfaces
Unit IV Packages&Interfaces
Packages are used to group the logical related classes and interfaces.
Packages help in avoiding name conflicts.
Ex: 1
package graphics;
class Circle{
…….
}
package graphics;
class Rectangle{
…….
}
A package statement should be written at the top of every source/ java file.
If a class doesn’t have the package statement, then the class is placed in the default
package, which is the current directory location.
Accessing a package: For example if we have created the above package graphics in
say d:\ java\ graphics\Circle.java
Then if we run the Circle.java program. It will first search for the class in the current
directory or in the location where the CLASSPATH environmental variable is set.
If we always run any java program from one level above the package level, then there is
no need to set the classpath variable.
But if we set the CLASSPATH variable, then we have to run the java programs from that
path.
Importing packages:
If a class Rectangle3D extends a class Rectangle existing in some other package, it has to
first import that package into the current package in order to use the classes in it.
Ex:
package graphics3D;
import graphics;
…..
}
import is the keyword used to access the classes or interfaces of one package into
another.
Ex 1:
interface Polygon{
float PI = 3.13f;
float area();
float circumference();
}
Implementing an Interface:
Ex 1 continued.
class PolygonUse{
public static void main(String args[]){
Circlew c= new Circle();
System..out.println(“Area of circle = ”+ c.area() );
System..out.println(“Circumference of circle = ”+ c.circumference() );
}
The class which implements an interface should give definitions to all its abstract
methods.
If the above Polygon class doesn’t give the implementation to all the abstract methods of
the interface, then the class has to be declared as abstract.
Classes Interfaces
1) Classes can be instantiated 1) Interfaces cannot be instantiated
2) Classes can have all types of data 2) Interfaces can have only final variables.
members.
3) One class can extend the function of 3) A class implements an interface using
another class using the extends keyword. the implements keyword.
4) Methods in classes are concrete/ 4) Methods in an interface are by default
abstract abstract
5) Classes are defined with keyword 5) Interfaces are defined using the keyword
“class”. “interface”
Extending interfaces:
An interface can extend another interface. Unlike classes, an interface can extend more
than one interface.
Ex:
interface A{
…..
}
interface B extends A{
…..
}
class C implements B{
……
}
Note: Multiple inheritance is not directly supported in java through classes, but can be
achieved using interfaces.