【问题标题】:Java - using the 'super' keywordJava - 使用“超级”关键字
【发布时间】:2023-03-23 08:40:01
【问题描述】:

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

这是Tester1:

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

如果我改为将第 5 行改为

super.ABC = "Hello"; 

我还在做同样的事情吗?

【问题讨论】:

  • 这实际上是一个好问题。 super 如何与被覆盖的方法一起工作是相当普遍的知识,但字段不同。

标签: java keyword super extends


【解决方案1】:

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

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
    }
}

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

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

      如果您也在 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
          }
      }
      

      【讨论】:

      • 除非它是静态的。 OP 实际上并没有说它不是静态的,但语气表明它可能不是。 :)
      • 它不是静态的。很好的例子和解释!
      【解决方案4】:

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

      【讨论】:

      • 我想只有当 Tester1 有一个成员变量 ABC 遮蔽超类 ABC 变量时才有意义。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 2017-01-08
      相关资源
      最近更新 更多