5

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

这是Tester1:

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

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

super.ABC = "Hello"; 

我还在做同样的事情吗?

4

4 回答 4

8

是的。您的对象中只有一个 ABC 变量。但请不要一开始就公开字段。字段几乎应该始终是私有的。

如果您ABC也在其中声明了一个变量Tester1那么就会有所不同- in 中的字段Tester1隐藏in 中的字段Tester2,但使用super您仍然会引用 .in 中的字段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
    }
}
于 2011-07-29T23:07:27.520 回答
2

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

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
    }
}
于 2011-07-29T23:12:41.657 回答
1

那么第一件事是该变量ABC必须在类中声明Tester2。如果是,那么是的。

于 2011-07-29T23:07:05.913 回答
1

你是。鉴于 ABC 对 Tester1(子类)可见,假定它被声明为除私有之外的任何内容,这就是它对子类可见的原因。在这种情况下,使用 super.ABC 只是加强了变量是在父项中定义的事实。

另一方面,如果 ABC 在父类中被标记为私有,则将无法从子类访问该变量 - 即使使用 super (当然,不使用一些花哨的反射)。

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

于 2011-07-29T23:11:15.413 回答