fweigl
fweigl

Reputation: 22038

Calling super() in constructor

I just used Eclipse's 'generate constructor using fields' function and it provided me with the following constructur:

public Credentials(String userName, String password) {
    super();
    this.userName = userName;
    this.password = password;
}

The Credentials class does not explicitly extend another class so it extends Object I guess. What is the super(); call good for?

Upvotes: 2

Views: 120

Answers (4)

christopher
christopher

Reputation: 27356

If you were to define your constructor as:

public Credentials(String userName, String password) {
    this.userName = userName;
    this.password = password;
}

Then the compiler will add an implicit call to the superclass constructor anyway, so this doesn't make ANY difference to the compiled code.

The Credentials class does not explicitly extend another class so it extends Object I guess. What is the super(); call good for?

But your class implicitly extends Object, so a call to Object() will be made.

Upvotes: 5

user902383
user902383

Reputation: 8640

super() calls parent class constructor, if you won't add this line, non arg constructor will be called by default.

If parent class does not have non-args constructor and you won't call other constructor, your code will not compile

Upvotes: 0

f1sh
f1sh

Reputation: 11942

The super keyword is a reference to the "enclosing" instance of the current superclass.

You can use it to either access the superclass's methods or fields (in case they are visible). If your class does not have a superclass (specified by class Credentials extends SuperclassName), the superclass is Object automatically.

super() as a method call invokes the superclass's constructor (the one with no arguments). You can only call in you own class's constructor(s), not in any other method.

Example:

class A {
  private String m_name;
  public A(String name){
    m_name = name;
  }
}

class B extends A {
  public B(String firstName, String lastName){
    //this calls the constructor of A
    super(firstName + " " + lastName);
  }
}

Upvotes: 1

Lucian Novac
Lucian Novac

Reputation: 1265

super() calls the parent constructor with no arguments.

To use if for arguments for example super(your argument) it will call the constructor that accepts one parameter of the type of argument (if extists).

Also it can be used to call methods from the parent. I.e. super.yourMethod()

Upvotes: 0

Related Questions