Java – 使用’super’关键字

简单的问题。 我创建了一个名为Tester1的类,它扩展了另一个名为Tester2的类。 Tester2包含一个名为’ABC’的公共字符串。

这是Tester1:

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

如果我改为第5行

 super.ABC = "Hello"; 

我还在做同样的事吗?

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

如果你在Tester1声明了一个变量ABC那么就会有区别Tester1的字段会隐藏 Tester1的字段,但是使用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 } } 

是的,超级限定符是不必要的,但工作原理相同。 澄清:

 public static class Fruit { protected String color; protected static int count; } public static class Apple extends Fruit { public Apple() { color = "red"; super.color = "red"; // Works the same count++; super.count++; // Works the same } } 

首先,必须在类Tester2声明变量ABC 。 如果是,那么你就是。

你是。 鉴于ABC对Tester1(子类)是可见的,假设它被声明为私有,这就是为什么它对子类可见。 在这种情况下,使用super.ABC只是强化了变量在父级中定义的事实。

另一方面,如果ABC在父类中被标记为私有,则无法从子类访问该变量 – 即使使用了super(当然也没有使用某些花哨的reflection)。

另外需要注意的是,如果变量已在父类中定义为私有,则可以在子类中定义具有完全相同名称的变量。 但同样,super不会授予您访问父变量的权限。