一。向上转型spa
向上转型是JAVA中的一种调用方式,是多态的一种表现。向上转型并不是是将B自动向上转型为A的对象,相反它是从另外一种角度去理解向上两字的:它是对A的对象的方法的扩充,即A的对象可访问B从A中继承来的和B重写A的方法,其它的方法都不能访问,包括A中的私有成员方法。code
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*/ } }
一、a实际上指向的是一个子类对象,因此能够访问Son类从Father类继承的方法sleep()和重写的方法eat()对象
二、因为向上转型,a对象会遗失和父类不一样的方法,如methods();blog
简记:A a = New B()是new的子类对象,父类的引用指向它。儿子本身挣的东西,父亲不能访问。父亲给儿子留下的(extends)或者儿子重写父亲的东西,父亲才能访问继承
答案:io
Father sleepfunction
son eatclass
二。静态方法不能算方法的重写扩展
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
向上转型的目的是规范和扩展,提升代码的维护性和扩展性