Java 父类 xx = new 子类()

package com.walter.test;

public class FatherNewSon {
	public static void main(String[] args) {
		Fu Fz = new Zi();
		Zi Zz = new Zi();
		Fz.name();
		//Fz.son();
		//The method son() is undefined for the type Fu
		Zz.name();
		Zz.son();
}
}

class Fu{
	public Fu(){
		
	}
	public void name(){
		System.out.println(this.getClass().getName());
	}
}

class Zi extends Fu{
	public Zi(){
		
	}
	public void son(){
		System.out.println("son");
	}
	
}

com.walter.test.Zi
com.walter.test.Zi
son

 其中Fz是由父类定义的指向子类对象的引用,Zz是由子类 xx = new 子类()定义的,然而Fz.son()却报错:没有该方法,而Zz.son()却不会报错。可见,父类 xx = new 子类()定义的对象无法调用非从父类继承的方法。此外,由运行结果:

   

    可见FZ.name()和Zz.name()都是调用b中的方法。

    以上总结出父类 xx = new 子类()与子类 xx = new 子类()的区别:

    1.父类 xx = new 子类()定义的对象只能调用继承来的方法。

    2.父类 xx = new 子类()定义的对象调用的是子类的方法,而不是父类的。

https://blog.csdn.net/nimeghbia/article/details/54766551

猜你喜欢

转载自blog.csdn.net/weixin_37704787/article/details/82183682