Lecture 14 Interfaces and Packages
Lecture 14 Interfaces and Packages
Technology
CIC-212 Java Programming
Interfaces, Packages
Interfaces
Concept
An interface is a way to describe what classes should
do, without specifying how they should do it. It’s not a class
but a set of requirements for classes that want to conform
to the interface
E.g. public interface Comparable
{
int compareTo(Object
otherObject);
}
interface A {
int val = 1;
}
interface B {
int val = 2;
}
interface C extends A, B {
System.out.println(“A.val = “+
A.val); System.out.println(“B.val = “+
B.val);
}
Tedious Details
If a superinterface and a subinterface contain two constants
with the same name, then the one belonging to the
superinterface is hidden.
1. in the subinterface
– access the subinterface-version constants by directly using its
name
– access the superinterface-version constants by using the
superinterface name followed by a dot and then the constant
name
interface X { Y‘s val
int val = 1; }
X’s val
interface Y extends X{
int val = 2;
int sum = val + X.val; }
2. outside the subinterface and the superinterface
– you can access both of the constants by explicitly giving the
interface name.
In previous example, use Y.val and Y.sum to access constants
val and sum of interface Y, and use X.val to access constant
val of interface X.
Tedious Details
When a superinterface and a subinterface contain two constants
with the same name, and a class implements the subinterface
– the class inherits the subinterface-version constants as its static
fields. Their access follow the rule of class’s static fields access.
class Z implements Y { }
//inside the class
System.out.println(“Z.val:“+val); //Z.val = 2
//outside the class
System.out.println(“Z.val:“+Z.val); //Z.val = 2
— object reference can be used to access the constants
subinterface-version constants are accessed by using the object
reference followed by a dot followed by the constant name
superinterface-version constants are accessed by explicit casting
Z v = new Z( );
System.out.print( “v.val = “ + v.val + “, ((Y)v).val = “ + ((Y)v).val
+“, ((X)v).val = “ + ((X)v).val );
JAVA PACKAGE
import java.awt.*;
import java.awt.Colour;