只问耕耘
分类: Java
2010-01-14 15:26:05
package c1;
interface I1{
public void p();
}//end interface I1//===================================//
interface I2 extends I1{
public void q();
}//end interface I2
public class Test{
public static void main(String[] args){
I1 var1 = new B();
var1.p();//OK
((I2)var1).q();//OK
I2 var2 = new B();
var2.p();//OK
var2.q();//OK
String var3 = ((A)var2).x();//OK
System.out.println(var3);
/*
* With respect to the eleven methods declared in the Object class (listed in an earlier lesson), a reference of an interface type acts like it is also of type Object.
*/
var3 = var2.toString();//OK
System.out.println(var3);
var2 = new C();
var2.p();//OK
var2.q();//OK
}
}
class A extends Object{
public String toString(){
return "toString in A";
}//end toString()
//---------------------------------//
public String x(){
return "x in A";
}//end x()
//---------------------------------//
}//end class A
class B extends A implements I2{
public void p(){
System.out.println("p in B");
}//end p()
//---------------------------------//
public void q(){
System.out.println("q in B");
}//end q();
//---------------------------------//
}//end class B
class C extends Object implements I2{
public void p(){
System.out.println("p in C");
}//end p()
//---------------------------------//
public void q(){
System.out.println("q in C");
}//end q();
//---------------------------------//
}//end class C
/*
输出结果:
p in B
q in B
p in B
q in B
x in A
toString in A
p in C
q in C
*/
/*
The cardinal rule
In case you have forgotten it, the cardinal rule for implementing interfaces is:
If a class implements an interface, it must provide a concrete definition for all the methods declared by that interface, and all the methods inherited by that interface. Otherwise, the class must be declared abstract and the definitions must be provided by a class that extends the abstract class.
*/