Java - using the 'super' keyword

2019-05-03 06:58发布

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?

4条回答
Animai°情兽
2楼-- · 2019-05-03 07:31

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

查看更多
甜甜的少女心
3楼-- · 2019-05-03 07:44

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
    }
}
查看更多
戒情不戒烟
4楼-- · 2019-05-03 07:46

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
    }
}
查看更多
放我归山
5楼-- · 2019-05-03 07:48

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.

查看更多
登录 后发表回答