黑马程序员技术交流社区

标题: 为什么是这个输出结果? [打印本页]

作者: lovecx24    时间: 2013-11-29 20:20
标题: 为什么是这个输出结果?
本帖最后由 lovecx24 于 2013-11-29 20:25 编辑

看Java 继承方面的知识看到上面有这么一个题,百思不得其解啊
  1. class Depend {
  2. int i = 10;

  3. public Depend() {
  4. print();
  5. i = 20;
  6. }

  7. void print() {
  8. System.out.println("Depend=> " + this.i);
  9. }
  10. }

  11. class Test1 extends Depend {
  12. int i = 30;

  13. public Test1() {
  14. print();
  15. super.print();
  16. i = 40;
  17. }

  18. void print() {
  19. System.out.println("Target=> " + i);
  20. }

  21. }
复制代码
  1. public class Test{
  2. public static void main(String[] args){
  3. new Test1();
  4. }
  5. }
复制代码

答案不是:
Depend=> 0
Target=> 30
Target=>20

答案居然是 :
Depend=>10
Target=> 30
Target=>20     子类实例都没有创建,就能调用子类方法吗?




作者: ysunday    时间: 2013-11-29 20:22
主函数在哪里?
作者: lovecx24    时间: 2013-11-29 20:23
程序入口是:
  1. public class Test{
  2. public static void main(String[] args){
  3. new Test1();
  4. }
  5. }
复制代码

作者: ysunday    时间: 2013-11-29 20:36
本帖最后由 ysunday 于 2013-11-29 20:37 编辑

new Test1()这个就是创建子类对象了。这句话就和 Test1 t = new Test1();是一样的,只不过这个new Test1()创建了一个每名字的对象而已。当你创建这个对象的时候,会调用Test1的构造方法
public Test1() {
//super();这里有个隐含的super()会去调用你的父类的构造函数,也就是第04行,父类构造函数调用了
               //父类的print,打印了depend -》10;然后执行i  = 20将父类中的i改变为20
print();    //然后执行这句,执行Test1的print,打印target—》30
super.print();//然后执行这句,执行父类的print,因为刚才你已经将父类的i = 20了,所以打印//target-》20喽
i = 40;
}





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2