Java - 使用“super”关键词
简单的问题。我创建了一个名为 Tester1 的类,它扩展了另一个名为 Tester2 的类。 Tester2 包含一个名为“ABC”的公共字符串。
这是 Tester1:
public class Tester1 extends Tester2
{
public Tester1()
{
ABC = "Hello";
}
}
如果我将第 5 行更改为,
super.ABC = "Hello";
我仍然在做完全相同的事情吗?
Simple question. I made a class called Tester1 which extends another called Tester2. Tester2 contains a public string called 'ABC'.
Here is Tester1:
public class Tester1 extends Tester2
{
public Tester1()
{
ABC = "Hello";
}
}
If I instead change line 5 to
super.ABC = "Hello";
am I still doing the exact same thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的。您的对象中只有一个 ABC 变量。但请不要首先将字段公开。字段几乎应该始终是私有的。
如果您也在
Tester1
中声明了变量ABC
,那么就会有差异 -Tester1
中的字段> 将隐藏Tester2
中的字段,但使用super
您仍然会引用Tester2
中的字段。但也不要这样做——隐藏变量是使代码变得难以维护的一种非常快速的方法。示例代码:
Yes. There's only one ABC variable within your object. But please don't make fields public in the first place. Fields should pretty much always be private.
If you declared a variable
ABC
withinTester1
as well, then there'd be a difference - the field inTester1
would hide the field inTester2
, but usingsuper
you'd still be referring to the field withinTester2
. But don't do that, either - hiding variables is a really quick way to make code unmaintainable.Sample code:
是的,超级限定符是不必要的,但作用是一样的。澄清一下:
Yes, the super qualifier is unnecessary but works the same. To clarify:
首先,变量
ABC
必须在类Tester2
中声明。如果是的话,那么你就是。Well first thing is that the variable
ABC
must be declared in the classTester2
. If it is then yes you are.你是。鉴于 ABC 对 Tester1(子类)可见,因此假定它被声明为除私有之外的任何内容,这就是它对子类可见的原因。在这种情况下,使用 super.ABC 只是强化了变量是在父级中定义的事实。
另一方面,如果 ABC 在父类中被标记为私有,则无法从子类访问该变量 - 即使使用 super (当然,不使用一些花哨的反射)。
另一件需要注意的事情是,如果变量在父类中被定义为私有,则可以在子类中定义一个具有完全相同名称的变量。但同样, super 不会授予您访问父变量的权限。
You are. Given that ABC is visible to Tester1 (the child class), it is assumed to be declared anything but private and that is why it is visible to a sub-class. In this case, using super.ABC is simply reinforcing the fact that the variable is defined in the parent.
If, on the other hand, ABC had been marked private in the parent class, there would be no way of accessing that variable from a child class - even if super is used (without using some fancy reflection, of course).
Another thing to note, is that if the variable had been defined private in the parent class, you could define a variable with the exact same name in the child class. But again, super would not grant you access to the parent variable.