接口实现中的小小问题,觉得很郁闷。。。
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 个错误