java面向对象19_多态中成员特点

1.多态中成员变量特点

无论编译和运行,都参考等号左边(引用类型变量所属的类)。

【示例】多态中成员变量特点

class Father {
	int num = 10;
}
class Son extends Father {
	int num = 20;
	String name = "小明";
}
public class InstanceDemo {
	public static void main(String[] args) {
		Father father = new Son();
		// 多态中的成员变量:无论编译和运行,都参考等号左边的类
		System.out.println("num:" + father.num); // 编译通过,输出父类中的num值
		// System.out.println("name:" + father.name); 编译错误
	}
}

2.多态中成员方法特点

编译看左边,参考等号左边引用对象所属的类是否有该方法。

运行看右边,在执行期间判断引用对象的实际类型,然后根据其实际的类型调用其相应的方法,又称为动态绑定

class Father {
	public void eat() {
		System.out.println("父类中的eat方法");
	}
}
class Son extends Father {
	public void study() {
		System.out.println("子类中的show方法");
	}
	public void eat() {
		System.out.println("子类中的eat方法");
	}
}
public class InstanceDemo {
	public static void main(String[] args) {
		Father father = new Son();
		father.eat(); // 编译通过,调用子类中的eat方法
		// father.study(); 编译错误
	}
}

ps:如需最新的免费文档资料和教学视频,请添加QQ群(627407545)领取。

发布了55 篇原创文章 · 获赞 0 · 访问量 789

猜你喜欢

转载自blog.csdn.net/zhoujunfeng121/article/details/104600496