向上转型---父类引用指向子类对象 A a = New B()的使用

一。向上转型

      向上转型是JAVA中的一种调用方式,是多态的一种表现。向上转型并非是将B自动向上转型为A的对象,相反它是从另一种角度去理解向上两字的:它是对A的对象的方法的扩充,即A的对象可访问B从A中继承来的和B重A的方法,其它的方法都不能访问,包括A中的私有成员方法。

 

class Father{
    
    public void sleep(){
        System.out.println("Father sleep");
    }
 
    public void eat() {
        System.out.println("Father eat");
    }
}
 
class Son extends Father {
    
    public void eat() {
        System.out.println("son eat");//重写父类方法
    }
    
    //子类定义了自己的新方法
    public void newMethods() {
        System.out.println("son method");
    }
}
 
public class Demo {
 
    public static void main(String[] args) {
        
        Father a = new Son();
        a.sleep();
        a.eat();
        
        //a.methods();    /*报错:The method methods() is undefined for the type Father*/
    }
}

1、a实际上指向的是一个子类对象,所以可以访问Son类从Father类继承的方法sleep()和重写的方法eat()

2、由于向上转型,a对象会遗失和父类不同的方法,如methods();

简记:A a = New B()是new的子类对象,父类的引用指向它。儿子自己挣的东西,父亲不能访问。父亲给儿子留下的(extends)或者儿子重写父亲的东西,父亲才能访问

答案:

Father sleep

son eat

二。静态方法不能算方法的重写

class Father {
    public int num = 100;
 
    public void show() {
        System.out.println("show Father");
    }
 
    public static void function() {
        System.out.println("function Father");
    }
}
 
class Son extends Father {
    public int num = 1000;
    public int num2 = 200;
 
    public void show() {
        System.out.println("show Son");
    }
 
    public void method() {
        System.out.println("method Son");
    }
 
    public static void function() {
        System.out.println("function Son");
    }
}
 
public class DuoTaiDemo {
    public static void main(String[] args) {
        // 要有父类引用指向子类对象。
        // 父 f = new 子();
        Father f = new Son();
        System.out.println(f.num);
        // 找不到符号
        // System.out.println(f.num2);
         f.show();
        // 找不到符号
        // f.method();
        f.function();
    }
}

答案:

100

show Son

function Father

向上转型的目的是规范和扩展,提高代码的维护性和扩展性

 

posted @ 2018-07-30 17:30  小宝的进化之路  阅读(696)  评论(0编辑  收藏  举报