public class Test {public static void main(String[] args) { Man p = new Man(); //Man p.printI(); //1 p.printII(); //0 }
}
class Person {
int i = 0;public Person(){ System.out.println(this.getClass()); } void printI(){ System.out.println(i); } void printII(){ System.out.println(i); }
}
class Man extends Person {
int i = 1;void printI(){ System.out.println(i); }
}
[color=red]那是因为 MAN 继承了Person,而man并没有构造函数,因此会继承person默认的无参构造函数。[/color]
[color=red]那是因为man 重写了 person的printI方法,调用man 的i。但是printII却没有。所以仍然调用的person的i;[/color]
[color=blue]
推荐楼主静下心来,好好的读一遍 thinking in java。
然后这些对你来说小菜。[/color]
这就是重载和继承的区别。
第一个问题是继承的问题(MAN继承了父类的构造方法,所以在MAN中虽然没写,但一样会默认生成该方法)
第二个问题是重载的问题( printI()是重写了,而 printII()是继承了)
LZ概念没有理清。
第一个问题:子类的构造器如果没有指明父类的构造器,会自动选择父类的默认无参构造器。
第二个问题:因为MAN覆盖了Person类的printI()方法,所以执行MAN.printI()的是否执行的是MAN的方法。
在构造函数中的this到底是指什么呢?
应是当前的实例
当前的实例就是子类