cristianix
cristianix

Reputation: 51

Calling Object's constructor

  1. Why should a class call the call the Objects default constructor of the class Objects when the class already has a parametrized constructor and a unparametrized constructor?

Example

public abstract class Foo{
    private int dim1;

    public Foo(int dim1) {
        super();
        this.dim1 = dim1;

    }
    public Foo() {

        this.dim1 = 0;

    }
}

2. Why isn't the super() method called in the unparametrized constructor in the example above?

  1. What could happen if I forget or I don't want to call the constructor in the Object class with super() ?

  2. Does it matter if the class which calls the super() method (Unparametrized Object's class constructor) is abstract or not ?

Upvotes: 0

Views: 498

Answers (2)

Michael
Michael

Reputation: 44100

1) You probably shouldn't. It is unnecessary. It is an extra line of code which doesn't do anything.

2) Because explicitly calling super() is entirely unnecessary if your object does not extend a class other than Object (as all classes do). You could remove it from the first constructor and nothing would change. The code would compile identically.

3) Nothing. You're not required to do it.

4) This makes no difference.

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

Why should a class call the call the Objects default constructor of the class Objects when the class already has a parametrized constructor and a unparametrized constructor?

Just because of you have it, it doesn't mean it gets called automatically. You have to call it and that is where object instantiation begins.

Why isn't the super() method called in the unparametrized constructor in the example above?

It is not a method. It is just invoking the super class default constructor. Do you know , if you didn't call it, the Java compiler automatically inserts that statement while giving you byte code. So you need not write that super() in child constructors unless you want to call specific constructor .

What could happen if I forget or I don't want to call the constructor in the Object class with super() ?

Don't worry. As said above, compiler inserts it for you.

Does it matter if the class which calls the super() method (Unparametrized Object's class constructor) is abstract or not ?

Yes, abstract or not doesn't matter. It just calls the super class constructor.

Upvotes: 2

Related Questions