zhangustb 2019-12-30 14:55 采纳率: 0%
浏览 435

当一个方法只在父类中定义时,为什么调用该方法时会使用父类中的属性

class Father {
private String name = "Father";
public String getName() {
return name;
}
}
class Child extends Father{
private String name = "child";
public static void main(String[] args) {
Child c = new Child();
System.out.println("输出结果:"+c.getName());
}
}

输出结果:Father
————————————————
当一个方法只在父类中定义时,为什么调用该方法时会使用父类中的属性?子类和父类有同名的属性,调用父类方法,用的属性为什么不是子类的?

  • 写回答

4条回答 默认 最新

  • 「已注销」 2019-12-30 15:05
    关注

    因为你的这个方法实际的写法应该为this.name,只不过this可写可不写,意思就是返回的为当前类中定义的name

    public String getName() {
            return name;
        }     
    
        public String getName() {
            return this.name;  //
        }
    

    如果你要使用子类的name就这么写

        class Father {
        private String name = "Father";
        public String getName(String name) {
            return name;
        }
    }
    class Child extends Father{
        private static String name = "child";
        public static void main(String[] args) {
            Child c = new Child();
            System.out.println("输出结果:"+c.getName(name));  //打印为child
        }
    }
    

    如果你要使用父类的就这么写

    class Father {
        private String name = "Father";
        public String getName(String name) {
            return this.name;
        }
    }
    class Child extends Father{
        private static String name = "child";
        public static void main(String[] args) {
            Child c = new Child();
            System.out.println("输出结果:"+c.getName(name));   //打印为father
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Linux权限管理相关操作(求解答)
  • ¥15 Bug traq 数据包 大概什么价
  • ¥15 在anaconda上pytorch和paddle paddle下载报错
  • ¥25 自动填写QQ腾讯文档收集表
  • ¥15 DbVisualizer Pro 12.0.7 sql commander光标错位 显示位置与实际不符
  • ¥15 求一份STM32F10X的I2S外设库
  • ¥15 android 打包报错
  • ¥15 关于stm32的问题
  • ¥15 ncode振动疲劳分析中,noisefloor如何影响PSD函数?