JAVA的向上转型 和 向下转型

  1. 向上转型 是面向对象继承的一种形式,是指子类对象转换为父类对象。

    看下面的example
    class Instrument {
        public void play() {
            System.out.println("Instrument play");
        }
        static void tune(Instrument i) {
            
            // …
            i.play();
        }
    }
    
    public class Test1 extends Instrument {
        public static void main(String [] args) {
        Test1 w = new Test1();
        Instrument.tune(w);
        }
    }
    
    
    // out put
    
    Instrument play 

            

            导出类转型为基类,在继承图上是向上移动的,因此一般称为向上转型。

            在向上转型的过程中,子类唯一可能发生的事情是丢失方法,子类的新有的方法都会丢掉。

  1.    向下转型: 父类引用的对象转换为子类类型称为向下转型。
       看下面的代码
      
    class Animal {
        public void eat() {
            System.out.println("Animal eat");
        }
    }
    
    class Dog extends Animal{
        
        @Override
        public void eat() {
            System.out.println("Dog eat");
        }
        
        public void cry() {
            System.out.println("Dog cry");
        }
    }
    
    public class Test1 {
        public static void main(String[] args) {
            Animal d1 = new Dog();
            d1.eat();
            
            Dog d = (Dog) d1;
            d.eat();
            d.cry();
            
            Animal d2 = new Animal();
            Dog d3 = (Dog) d2;
            d3.eat();
            d3.cry();
        }
    }

            向下转型

    
   1、父类引用可以指向子类对象,子类引用不能指向父类对象。

            2、把子类对象直接赋给父类引用叫upcasting向上转型,向上转型不用强制转型。

           如Father father = new Son();

            3、把指向子类对象的父类引用赋给子类引用叫向下转型(downcasting),要强制转型。

           如father就是一个指向子类对象的父类引用,把father赋给子类引用son 即Son son =(Son)father;

           其中father前面的(Son)必须添加,进行强制转换。

            4、upcasting 会丢失子类特有的方法,但是子类overriding 父类的方法,子类方法有效

            5、向上转型的作用,减少重复代码,父类为参数,调有时用子类作为参数,就是利用了向上转型。这样使代码变得简洁。体现了JAVA的抽象编程思想。

猜你喜欢

转载自blog.csdn.net/qq_39467629/article/details/81116226