Java - using the 'super' keyword

大憨熊 提交于 2019-12-22 06:59:21

问题


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?


回答1:


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 within Tester1 as well, then there'd be a difference - the field in Tester1 would hide the field in Tester2, but using super you'd still be referring to the field within Tester2. But don't do that, either - hiding variables is a really quick way to make code unmaintainable.

Sample code:

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



回答2:


Yes, the super qualifier is unnecessary but works the same. To clarify:

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



回答3:


Well first thing is that the variable ABC must be declared in the class Tester2. If it is then yes you are.




回答4:


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.



来源:https://stackoverflow.com/questions/6879892/java-using-the-super-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!