刚刚在看《深入浅出java虚拟机》的时候,发现了一个比较不错的题目,分享一下:class Superclass{
public Superclass(){
interestingMehod();
}
void exampleMethod(){
interestingMehod();
}
private void interestingMehod(){ //注释
System.out.println(
"Superclass's interesting method.");
}
}class Subclass extends Superclass{
public Subclass(){
interestingMehod();
}
public void interestingMehod(){
System.out.println(
"Subclass' interesting method.");
}
}
//Test.java
public class Test{
public static void main(String[] args){
Subclass me = new Subclass();
me.exampleMethod();
}
}上面的代码输出什么呢?然后把“注释”处的函数的private改为protected,public或直接去掉,又怎么样呢?
public Superclass(){
interestingMehod();
}
void exampleMethod(){
interestingMehod();
}
private void interestingMehod(){ //注释
System.out.println(
"Superclass's interesting method.");
}
}class Subclass extends Superclass{
public Subclass(){
interestingMehod();
}
public void interestingMehod(){
System.out.println(
"Subclass' interesting method.");
}
}
//Test.java
public class Test{
public static void main(String[] args){
Subclass me = new Subclass();
me.exampleMethod();
}
}上面的代码输出什么呢?然后把“注释”处的函数的private改为protected,public或直接去掉,又怎么样呢?
不运行程序的话,觉得是这个结果
"Superclass's interesting method.
"Subclass' interesting method.
"Superclass's interesting method.
Subclass' interesting method.
Superclass's interesting method.一楼忘了 Subclass me = new Subclass();
就是重写父类方法了
Subclass' interesting method.
Subclass' interesting method.
Subclass' interesting method.
没有看清楚private关键字,还以为方法被重写了呢
输出都是
Superclass's interesting method.
Subclass' interesting method.
Superclass's interesting method.
"Superclass's interesting method".
"Subclass' interesting method."
"Superclass's interesting method".
更改后,我觉得是
"Subclass' interesting method."
"Subclass' interesting method."
"Subclass' interesting method."
zheng jia renqi
Superclass's interesting method.
Subclass' interesting method.
Superclass's interesting method.分析:
创建一个对象并对其实例化
Subclass me = new Subclass();
实例化的过程是:执行构造函数
public Subclass(){
interestingMehod();
}因为构造函数继承Superclass类
所以调用Superclass中interestingMehod();方法
然后执行构造函数第二个方法
public void interestingMehod(){
System.out.println(
"Subclass' interesting method.");
最后使用对象。方法执行方法
要是弄懂这个问题最好是去C++的继承 你就明白了
Subclass' interesting method.
Superclass's interesting method.
Superclass's interesting method.
Subclass' interesting method.
Superclass's interesting method.
改过之后全部是:
Subclass' interesting method.不改:
1. 调用之类构造函数前要调用父类的构造函数,所以先调用父类的interestingMehod(),
然后调用子类的interestingMehod(),然后再调用父类的exampleMethod()。
Subclass' interesting method.
Superclass's interesting method. 说明: 在任何情况下, 如果父类有无参的构造函数, 那么先运行父类的构造函数,再运行子类的构造函数
Subclass' interesting method.
Superclass's interesting method.