Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2066347
  • 博文数量: 519
  • 博客积分: 10070
  • 博客等级: 上将
  • 技术积分: 3985
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-29 14:05
个人简介

只问耕耘

文章分类

全部博文(519)

文章存档

2016年(1)

2013年(5)

2011年(46)

2010年(220)

2009年(51)

2008年(39)

2007年(141)

2006年(16)

我的朋友

分类: 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.
*/

阅读(401) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~