父类和子类同名成员变量和同名成员函数

 1 package day3;
 2 
 3 /**
 4  * This program tests the condition that there are identical var , method in superclass and childclass.
 5  * @author Administrator
 6  *
 7  */
 8 public class SameVarAndMethodTest1 {
 9 
10     public static void main(String[] args) {
11         Parent1 p = new Child1();
12         System.out.println(p.name);
13         p.printName();
14         p.tellName();
15 //        Child1 c = new Child1();
16 //        System.out.println(c.name);
17 //        c.printName();
18 //        c.tellName();
19     }
20 
21 }
22 
23 class Parent1{
24      String name = "parent";
25     public Parent1(){
26         printName();
27         tellName();
28     }
29     public void printName(){
30         System.out.println("Parent printName:"+name);
31     }
32     public void tellName(){
33         System.out.println("Parent tellName:"+name);
34     }
35     public String getName(){
36         return name;
37     }
38 }
39 
40 class Child1 extends Parent1{
41      String name = "child";
42     public Child1(){
43         super();
44         printName();
45         tellName();
46     }
47     public void printName(){
48         System.out.println("Child printName:"+name);
49     }
50     public void tellName(){
51         System.out.println("Child tellName:"+name);
52     }
53     public String getName(){
54         return name;
55     }
56 }

以下是输出结果:

这是一道面试题,当时很懵逼。后来回来自己code一下,对于输出结果有两个疑问:第一,为什么在执行super()的时候,不是执行父类里的printName()和tellName()方法,而是执行子类里的;第二,既然执行子类里的printName()和tellName()方法,为什么name的值是null。目前还是不能理解,先把问题放这里,以后再来看看。

厚积薄发
原文地址:https://www.cnblogs.com/xinfengzi/p/7087260.html