`
shuidexiongdi
  • 浏览: 71721 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

继承、覆盖是你期望的执行结果吗

阅读更多
下面例子摘自《深入JAVA虚拟机第二版》第19章,P354
PS:本文不做结果解释,原因请参考作者的解释。只描述结果
package com.shuidexiongdi.thread;

public class SuperTest {
	public static void main(String[] args) {
		new Sub().exampleMethod();
	}
}

class Super {
	private void interestingMethod() {
		System.out.println("Super's interestingMethod");
	}
	
	void exampleMethod() {
		interestingMethod();
	}
}

class Sub extends Super {
	void interestingMethod() {
		System.out.println("Sub's interestingMethod");
	}
}

上面代码运行结果是?你的认为是?好吧,自己动手验证一下。
结果如下:
Super's interestingMethod

如果验证和自己想法一致的,恭喜你,你的基础还不错。我们接着对例子进行修改。

我们对上面例子中的Sub类进行修改
class Sub extends Super {
	void interestingMethod() {
		System.out.println("Sub's interestingMethod");
	}
	void exampleMethod() {
		interestingMethod();
	}
}

好了,上面的运行结果呢?和没修改前一致?还是动手试试吧。
运行结果如下:
Sub's interestingMethod

原因请参考作者原著的解释了,这里只是想提醒一下,继承在没有覆盖父类方法的情况下,定义一个与父类方法相同签名的私有方法(而这种情况我们会有意无意的发生着),请校验和期望的一不一致。不要简单的认为父类的方法纯碎就是拷贝到子类类体下。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics