当前位置: 代码迷 >> Java相关 >> 接口实现中的小小问题,觉得很郁闷。。。
  详细解决方案

接口实现中的小小问题,觉得很郁闷。。。

热度:256   发布时间:2011-11-15 21:39:24.0
接口实现中的小小问题,觉得很郁闷。。。
interface Singer {
    public static final int id = 0 ;  //可省略写成 int id = 0 ;
    public void sing() ;
    public void sleep() ;
}

interface Painter {
    public void paint() ;
    public void eat() ;
}

class Student implements Singer {
    public void sing() {
        System.out.println("student is singing ...") ;
    }
   
    public void sleep() {
        System.out.println("student is sleeping ...") ;
    }
   
    public void study() {
        System.out.println("student is studying ...") ;
    }
}

class Teacher implements Singer , Painter {
    public void sing() {
        System.out.println("teacher is singing ...") ;
    }
   
    public void sleep() {
        System.out.println("teacher is sleeping ...") ;
    }
   
    public void paint() {
        System.out.println("teacher is painting ...") ;
    }
   
    public void eat() {
        System.out.println("teacher is eatting ...") ;
    }
   
    public void teach() {
        System.out.println("teacher is teach ...") ;
    }
}

public class TestInterface {
    public static void main(String args[]) {
        Singer s1 = new Student() ;
        Painter p1 = new Teacher() ;   
        s1.sing() ;
        s1.sleep() ;
        p1.paint() ;
        p1.eat() ;
        
        Student s2 =  (Student)s1 ;
        s2.sing() ;
        s2.sleep() ;
        s2.study() ;
        
        Teacher p2 = (Teacher)p1 ;
        p2.sing() ;
        p2.sleep() ;
        p2.paint() ;
        p2.eat() ;
        p2.teach() ;
        
        System.out.println("s1.id = " + s1.id) ;
        System.out.println("s2.id = " + s2.id) ;
        //System.out.println("p1.id = " + p1.id) ;  //此句加上编译就不能通过,
                                                    //为什么System.out.println("s1.id = " + s1.id) ;可以呢,求解!!!
        System.out.println("p2.id = " + p2.id) ;
    }
}

提示错误为:
TestInterface.java:71: 错误: 找不到符号
                System.out.println("p1.id = " + p1.id) ;
                                                  ^
  符号:   变量 id
  位置: 类型为Painter的变量 p1
1 个错误
搜索更多相关的解决方案: 接口  interface  singing  public  

----------------解决方案--------------------------------------------------------
因为p1虽然实际指向的是Teacher类,但是p1的类型为Painter,Painter接口中是没有id属性的,所以p1.id,编译器在Painter找不到id,报错
p2为(Teacher)p1,即p1强转为Teacher类,因为p1实际上就是Teacher类,所以可以强转,那么实际上p2跟p1从是完全一样的,但p2是Teacher类的引用,Teacher类实现了Singer接口,所以p2.id是可以的.
s1本身就是Singer接口的引用,而id就是定义在Singer中,所以s1.id完全没有问题
----------------解决方案--------------------------------------------------------
顶2楼
----------------解决方案--------------------------------------------------------
回复 2楼 yhlvht
不好意思,我忘记了“Painter接口中是没有id属性的”,呵呵,谢谢提醒啊!!!
----------------解决方案--------------------------------------------------------
。。
----------------解决方案--------------------------------------------------------
  相关解决方案