interface Singer {
public void sing();
public void sleep();
}
interface Painter {
public void paint();
public void eat();
}
class Student implements Singer {
private String name;
Student(String name) {
this.name = name;
}
public void sing() {
System.out.println("student is singing");
}
public void sleep() {
System.out.println("student is sleeping");
}
}
class Teacher implements Singer,Painter {
private String name;
Teacher(String name) {
this.name = name;
}
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 eating"); }
}
public class Test {
public static void main(String args[]) {
Singer s1 = new Student("chenfei");
s1.sing();s1.sleep();s1.study();
Singer s2 = new Teacher("xiong");
s2.sing();s2.sleep();
Painter p1 = (Painter)s2;
p1.paint();p1.eat();
}
}
这个程序里 Painter p1 = (Painter)s2; 这句话将s2这个Teacher对象强制转换成painter类,那么p1就指向一个painter类对象了,就不存在基类引用指向子类对象了,为什么下面的p1.paint();这个方法还能执行出teacher is painting呢??