Java 要用子类的新方法就不要发生多态

举例: 


public class Test {

	public static void main(String[] args) {
		People people = new Student();
		people.say();
		//people.say2();//会报错:The method say2() is undefined for the type People
		System.out.println("-----");
		Student s = new Student();
		s.say();
		s.say2();
	}

}

abstract class People{
	abstract void say();
}

class Student extends People{
	@Override
	void say() {
		System.out.println("我是人");
	}
	
	void say2() {
		System.out.println("我是学生");
	}
}

输出结果:

我是人
-----
我是人
我是学生

当子类继承父类的时候,如果子类有新的方法并且要使用,不要发生多态,否则就只能用父类的方法,子类的新方法没法用。 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值