JAVA-上转型对象,下转型对象

package com.example.barry;
//父类
public class parents {
    
    

    public parents(){
    
    

    }
    public void say(){
    
    
        System.out.println("我是家长");
    }

    public void mysay(){
    
    
        System.out.println("家长测试一下");
    }
}


package com.example.barry;
//子类
public class child extends parents{
    
    

    public void say(){
    
    
        System.out.println("我是孩子");
    }

    public void my(){
    
    
        System.out.println("孩子自己方法");
    }
}



package com.example.barry;

public class Application {
    
    
    public static void main(String args[]){
    
    
    	//上转型
        parents p = new child();
        p.say();
        p.mysay();

		//下转型
        parents p1 = new child();
        child son = (child) p1;
        son.my();
        son.say();
        son.mysay();
    }
}


1、上转型对象

(1)上转型对象只能使用子类重写父类的方法
(2)上转型对象不能使用子类心新增加的方法

2、下转型对象
(1)下转型对象是声明父亲类对象,再强制转化为孩子类对象。
(2)下转型对象可以使用父类所有方法,并可以使用孩子新增加的方法。

猜你喜欢

转载自blog.csdn.net/xdg15294969271/article/details/121307466