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?
Well first thing is that the variable
ABC
must be declared in the classTester2
. If it is then yes you are.Yes, the super qualifier is unnecessary but works the same. To clarify:
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
withinTester1
as well, then there'd be a difference - the field inTester1
would hide the field inTester2
, but usingsuper
you'd still be referring to the field withinTester2
. But don't do that, either - hiding variables is a really quick way to make code unmaintainable.Sample code:
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.