[java] 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?

This question is related to java inheritance super

The answer is


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



I just tried it, commenting super(); does the same thing without commenting it as @Mark Peters said

package javaapplication6;

/**
 *
 * @author sborusu
 */
public class Super_Test {
    Super_Test(){
        System.out.println("This is super class, no object is created");
    }
}
class Super_sub extends Super_Test{
    Super_sub(){
       super();
       System.out.println("This is sub class, object is created");
    }
    public static void main(String args[]){
        new Super_sub();
    }
}

You could use it to call a superclass's method (such as when you are overriding such a method, super.foo() etc) -- this would allow you to keep that functionality and add on to it with whatever else you have in the overriden method.


From oracle documentation page:

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super.

You can also use super to refer to a hidden field (although hiding fields is discouraged).

Use of super in constructor of subclasses:

Invocation of a superclass constructor must be the first line in the subclass constructor.

The syntax for calling a superclass constructor is

super();  

or:

super(parameter list);

With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.

Related post:

Polymorphism vs Overriding vs Overloading


You call super() to specifically run a constructor of your superclass. Given that a class can have multiple constructors, you can either call a specific constructor using super() or super(param,param) oder you can let Java handle that and call the standard constructor. Remember that classes that follow a class hierarchy follow the "is-a" relationship.


You would use it as the first line of a subclass constructor to call the constructor of its parent class.

For example:

public class TheSuper{
    public TheSuper(){
        eatCake();
    }
}

public class TheSub extends TheSuper{
    public TheSub(){
        super();
        eatMoreCake();
    }
}

Constructing an instance of TheSub would call both eatCake() and eatMoreCake()


You may also use the super keyword in the sub class when you want to invoke a method from the parent class when you have overridden it in the subclass.

Example:

public class CellPhone {
    public void print() {
        System.out.println("I'm a cellphone");
    }
}

public class TouchPhone extends CellPhone {
    @Override
    public void print() {
        super.print();
        System.out.println("I'm a touch screen cellphone");
    }
    public static void main (strings[] args) {
        TouchPhone p = new TouchPhone();
        p.print();
    }
}

Here, the line super.print() invokes the print() method of the superclass CellPhone. The output will be:

I'm a cellphone
I'm a touch screen cellphone

When you want the super class constructor to be called - to initialize the fields within it. Take a look at this article for an understanding of when to use it:

http://download.oracle.com/javase/tutorial/java/IandI/super.html


The first line of your subclass' constructor must be a call to super() to ensure that the constructor of the superclass is called.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to inheritance

How to extend / inherit components? Inheritance with base class constructor with parameters Class is not abstract and does not override abstract method Why not inherit from List<T>? Can an interface extend multiple interfaces in Java? How to call Base Class's __init__ method from the child class? How should I have explained the difference between an Interface and an Abstract class? JavaScript OOP in NodeJS: how? When do I have to use interfaces instead of abstract classes? C++ calling base class constructors

Examples related to super

Equivalent of Super Keyword in C# super() raises "TypeError: must be type, not classobj" for new-style class Java: Calling a super method which calls an overridden method When do I use super()? super() in Java What is PECS (Producer Extends Consumer Super)? super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object Understanding Python super() with __init__() methods What does 'super' do in Python?