Java的上转型与下转型对象

上转型对象:将子类对象赋值给父类对象。例如:Father f = new Son。此时对象p可以调用子类中所继承的父类的属性和方法(不能调用子类新增的方法和属性)。

下转型对象:通过强制类型转换将经过了上转型的对象赋值给子类。例如 Son s = (Son)f。此时对象s可以调用子类中新增的方法和属性。

class Father{
    int n = 1;
    void FatherMethod(){
        System.out.println("调用父类的方法");
    }
}
class Son extends Father{
    //子类中与父类同名的属性,此时父类的属性被隐藏,可通过super关键字调用
    int n=2;
    //子类重写父类的方法
    void FatherMethod(){
        System.out.println("调用子类重写的方法");
    }
    void SonMethod(){
        System.out.println("调用子类新增的方法");
    }
}
public class Test {
    public static void main(String[] args) {
        //f1为上转型对象
        Father f1 = new Son();
        //上转型对象调用子类继承父类的方法,此时调用的是子类重写了父类的方法
        f1.FatherMethod();
        //输出上转型对象中的属性(即父类的)
        System.out.println(f1.n);
        
        //s1为下转型对象,强制类型转换只能是上转型的对象
        Son s1 = (Son) f1;
        //s1调用子类中重写的方法
        s1.FatherMethod();
        //s1调用子类新增的方法
        s1.SonMethod();
        //输出下转型对象中的属性(即子类的)
        System.out.println(s1.n);
    }
}

输出结果为:

调用子类重写的方法
1
调用子类重写的方法
调用子类新增的方法
2

  

posted @ 2021-04-03 18:06  我的成功之路  阅读(618)  评论(0)    收藏  举报