Java - 使用 'super' 关键字

标签 java keyword super extends

简单的问题。我制作了一个名为 Tester1 的类,它扩展了另一个名为 Tester2 的类。 Tester2 包含一个名为“ABC”的公共(public)字符串。

这是测试人员 1:

public class Tester1 extends Tester2
{
    public Tester1()
    {
         ABC = "Hello";
    }
}

如果我改为将第 5 行更改为

super.ABC = "Hello"; 

我还在做同样的事情吗?

最佳答案

是的。您的对象中只有一个 ABC 变量。但是请不要首先公开字段。字段应该几乎总是私有(private)的。

如果您也在 Tester1 中声明了一个变量 ABC那么就会有所不同 - Tester1 中的字段隐藏 Tester2 中的字段,但是使用 super 您仍然会引用 Tester2< 中的字段。但也不要那样做 - 隐藏变量是使代码无法维护的一种非常快速的方法。

示例代码:

// Please don't write code like this. It's horrible.
class Super {
   public int x;
}

class Sub extends Super {
    public int x;

    public Sub() {
        x = 10;
        super.x = 5;
    }

}

public class Test {
    public static void main(String[] args) {
        Sub sub = new Sub();
        Super sup = sub;
        System.out.println(sub.x); // Prints 10
        System.out.println(sup.x); // Prints 5
    }
}

关于Java - 使用 'super' 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6879892/

相关文章:

ruby - 我如何调用祖 parent 的方法,并在 ruby​​ 中跳过 parent

java - 在单行中初始化列表

java - 如果我们不知道容器类型中元素的类型,如何实现迭代器?

java - 如何使用 firebase 身份验证创建用户名、地址和详细信息

c# - 在 C# 中有没有办法以旧的 Pascal "with"关键字方式访问对象属性?

python 3 : super() raises TypeError unexpectedly

java - struts2 session 维护

python - 在单元测试的上下文中,python 关键字 "is"与函数 id() 相同吗?

sharepoint - 如何在 Sharepoint Foundation 2010 wiki 中分类和/或使用关键字?

python - 在 Python 2.7 中,通过 super(self.__class__, self)... 调用 super 构造函数不是更好吗?