public class Father {
public void eat(){
System.out.println("father吃饭");
}
public void sleep(){
System.out.println("father睡觉");
}
}
public class Son extends Father{
@Override
public void eat() {
System.out.println("son吃饭");
}
public void study(){
System.out.println("son学习");
}
}
public class Daughter extends Father{
@Override
public void eat() {
System.out.println("daughter吃饭");
}
public void study(){
System.out.println("daughter学习");
}
}
public class Test {
public static void main(String[] args) {
Father father = new Son();//上转型(父类引用指向子类对象。)
father.eat();//调用子类重写的方法
father.sleep();//调用父类方法
// father.study();//不能调用子类特有的方法
System.out.println("======================================================");
Son son = (Son) father;//下转型
son.eat();//调用子类重写的方法
son.sleep();//调用继承自父类的方法
son.study();//调用子类特有的方法
System.out.println("======================================================");
//上转型的好处,可以只定义一个eat方法,却可以同时接受Son和Daughter的对象作为实参。
eat(new Son());
eat(new Daughter());
}
public static void eat(Father father){
father.eat();
}
}
son吃饭
father睡觉======================================================
son吃饭
father睡觉
son学习======================================================
son吃饭
daughter吃饭