I'm currently learning about class inheritance in my Java course and I don't understand when to use the super()
call?
Edit:
I found this example of code where super.variable
is used:
class A { int k = 10; } class Test extends A { public void m() { System.out.println(super.k); } }
So I understand that here, you must use super
to access the k
variable in the super-class. However, in any other case, what does super();
do? On its own?
The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
However, using super() is not compulsory. Even if super() is not used in the subclass constructor, the compiler implicitly calls the default constructor of the superclass.
Calling exactly super() is always redundant. It's explicitly doing what would be implicitly done otherwise. That's because if you omit a call to the super constructor, the no-argument super constructor will be invoked automatically anyway.
We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields. In the above example, Animal and Dog both classes have a common property color. If we print color property, it will print the color of current class by default.
super
is used to call the constructor
, methods
and properties
of parent class.
Calling exactly super()
is always redundant. It's explicitly doing what would be implicitly done otherwise. That's because if you omit a call to the super constructor, the no-argument super constructor will be invoked automatically anyway. Not to say that it's bad style; some people like being explicit.
However, where it becomes useful is when the super constructor takes arguments that you want to pass in from the subclass.
public class Animal { private final String noise; protected Animal(String noise) { this.noise = noise; } public void makeNoise() { System.out.println(noise); } } public class Pig extends Animal { public Pig() { super("Oink"); } }
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