`
清风_夕瑶
  • 浏览: 53031 次
  • 性别: Icon_minigender_1
  • 来自: 潘多拉星球
社区版块
存档分类
最新评论

多态解疑

阅读更多

面试时,遇到子类对父类重写,但方法参数是这样的父类: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 -->

 
  • 大小: 7.6 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics