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?
Uses of super keywordTo call methods of the superclass that is overridden in the subclass. To access attributes (fields) of the superclass if both superclass and subclass have attributes with the same name. To explicitly call superclass no-arg (default) or parameterized constructor from the subclass constructor.
No, we cannot use this() and super() in a method in java. can a constructor call another constructor java?
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
}
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With