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

 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值