多态解疑

面试时,遇到子类对父类重写,但方法参数是这样的父类:test(Parent p),子类中test(Child c).子类在调用是c.test(p),,一时难以断定是子类是否重写了父类的方法。想想参数不一样,不应该是重写;反过来,但子类也是父类啊。难以断定,算了不是复写,先碰碰运气,回去后测试一下。回来后,测试了一下,还真不是复写,对多态算是又掌握了一些。

附上测试代码

class MyParent{
	int x, y;
	public MyParent(int x,int y){
		this.x = x;
		this.y = y;
	}
	public void test(MyParent my){
		System.out.println("-------父------");
		System.out.println(my.x+"----"+my.y);
	}
}
class MyChild extends MyParent{
	int z;
	public MyChild(int x, int y,int z) {
		super(x, y);
		this.z = z;
	}
	public void test(MyChild my){
		System.out.println("-------子------");
		System.out.println(my.x+"---"+my.y);
	}
	public static void main(String[] args) {
		MyParent p = new MyParent(10, 20);
		MyChild  c = new MyChild(100, 200, 300);
		p.test(c);
		p.test(p);
		c.test(c);
		c.test(p);
	}

 结果:<!--StartFragment -->

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值