Java字段隐藏属性 [英] Java field hiding for attributes

查看:65
本文介绍了Java字段隐藏属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习Java,因此,如果答案很明显,请耐心等待.我做了一些研究,但无济于事.

I just started to learn Java, so please bear with me if the answer is somewhat obvious. I did some research but no avail.

据我了解,属性不会被覆盖,而只会隐藏字段.为了确定是使用超类还是子类中的属性,Java将检查引用的类型.

From what I understand, attributes are not overriden but only field hidden. To determine whether the attribute in the superclass or the subclass is used, Java will check the type of the reference.

然后我不明白这里的输出:

Then I don't under stand the output here:

public class Super {
    String str = "I'm super!\n";

    public String toString() {
        return str;
    }
}

public class Sub extends Super {
    String str = "I'm sub.\n";
}

public class TestFH {
    public static void main(String[] args) {
        Sub s1 = new Sub();

        System.out.printf(s1.toString());
    }
}

它给了我

I'm super!

我了解可以通过方法重写轻松实现我想要的目标.我很好奇引擎盖下发生了什么.

I understand that I can achieve what I want easily via method overriding. I'm just curious about what's happenning under the hood.

谢谢.

推荐答案

调用 s1.toString()时,会发现仅在以下位置定义的 toString()方法 Super 类,因此在子类中可以使用该方法作为超类方法.您的超类方法 toString()使用它自己的类变量 str (其值在超类中初始化)作为该方法的返回值因此行为即输出为 I'm super!.

When you call, s1.toString(), it's finding toString() method defined only in Super class hence using that method as super class methods are available in the sub class. Your super class method toString() is using it's own class variable str (with value initialized in super class) as the return value from the method and hence the behavior i.e. output as I'm super!.

如果要以 I'm sub.\ n 作为输出,则需要重用与超类相同的变量,并分配新的字符串值,即 I'm子.\ n .最好的选择是将构造函数用作:

If you want to get the output as I'm sub.\n then you need to reuse the same variable as in the super class and assign the new string value i.e. I'm sub.\n to it. Best option is to use constructors as:

  public class Super {
     String str = "I'm super!\n";

     public Super(String stringValue){
         this.str = stringValue;
     }

     public String toString() {
        return str;
     }
  }

  public class Sub extends Super {
     public Sub(){
       super("I'm sub.\n");
     }
  }

  public class TestFH {
    public static void main(String[] args) {
       Sub s1 = new Sub();
       System.out.printf(s1.toString());
    }
  }

这篇关于Java字段隐藏属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆