COM 3118
April 2, 2001
Interfaces
Interface does not actually define any implementation.
Similar to abstract class.
A class can extend only one class.
A class can implement more than one interface.
Defining Interface
access interface name {
return-type method-name1(param-list);
return-type method-name2(param-list);
type final-variable-name1 = value;
type final-variable-name2 = value;
…..
}
access is either public or not used.
There can be no default implementation of methods.
Essentially abstract methods.
Methods have no bodies.
They end with a semi-colon after the parameter list.
Variables implicitly final and static.
Variables must be initialized.
Implementing Interfaces
Access class classname [extends superclass]
[implements interface [,interface..]] {
//class-body
}
access is either public or not used.
When you implement interface method, it must be declared public.
Partial implementations
abstract class Incomplete implements myInterface{
//.....
//….
}
Interfaces can be extended
interface A{
void method1();
void method2();
}
interface B extends A{
void method3();
}
class MyClass implements B {
public void method1() {
System.out.println("Implements method1.");
}
public void method2() {
System.out.println("Implements method2.");
}
public void method3() {
System.out.println("Implements method3.");
}
public void method4() {
System.out.println("New method added.");
}
}
class MyClass1 {
public static void main (String args[]) {
B b = new MyClass () ;
B.method3 () ;
B.method4 () ; // error, can’t access any other members of MyClass
// except those defined in interface B
}
}
Variables in Interfaces
interface SharedConstants {
int WRONG = 0;
int RIGHT = 1;
int MAYBE = 2;
int PROBABLY = 3;
}