Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I use super()?

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?

like image 796
muttley91 Avatar asked Nov 03 '10 19:11

muttley91


People also ask

What is super () is used for?

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.

Is super () necessary Java?

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.

Is super () necessary?

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.

What are the conditions for using super () method?

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.


2 Answers

super is used to call the constructor, methods and properties of parent class.

like image 40
Zain Shaikh Avatar answered Oct 05 '22 23:10

Zain Shaikh


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");     } } 
like image 100
Mark Peters Avatar answered Oct 06 '22 00:10

Mark Peters