Suhaib Ahmad
Suhaib Ahmad

Reputation: 526

Which super constructor will be called? And is super constructor still invoked if i don't invoke a super constructor in subclass?

public class Faculty extends Employee {
    public static void main(String[] args) {
        new Faculty();
    }

    public Faculty() {
        super(“faculty”);
    }
}

class Employee extends Person {
     private String name;
     public Employee() {
     name = “no name”;
     System.out.println("(3) Employee's no-arg constructor is invoked");
     }

     public Employee(String s) {
     name = s;
     System.out.println(s);
     }
}

class Person {
    //What if there was a parameterized constructor here
    // e.g. public Person(String s){
    //            ... code ...
    //      }
}

In the above Java code, if i leave the Person class blank, and call super constructor in Faculty class' no-arg constructor, Employee's constructor would be called. But what if there is a parameterized constructor in the Person class. Which super constructor will be called? Employee one or Person one?

And is super constructor still invoked if i don't invoke a super constructor in subclass?

Upvotes: 0

Views: 102

Answers (2)

user3437460
user3437460

Reputation: 17454

But what if there is a parameterized constructor in the Person class.

If you do that, you get a nice compilation error.

If your super class constructor has a parameter, your subclass shall invoke super(arguments) where arguments matches the parameter.

If the super class constructor does not have any parameters, your child class will implicitly invoke super(). Hence we don't have to explicitly invoke super() again.

Example:

class GrandParent
{
    public GrandParent(String s){
        System.out.println("Calling my grandpa");
    }
}

class Parent extends GrandParent
{
    public Parent(){
        super("");
        System.out.println("Calling my pa");
    }   
}

class Child extends Parent
{
    public Child(){
        //super() implicitly invoked
        System.out.println("Calling my child"); 
    }
}

Upon running the following:

class Test
{
    public static void main(String[] args){
        new Child();
    }
}

You get:

Calling my grandpa
Calling my pa
Calling my child

The above output answers your subsequent questions:

Employee one or Person one? And is super constructor still invoked if i don't invoke a super constructor in subclass?

Upvotes: 0

Mena
Mena

Reputation: 48404

Your Employee class won't compile if you add a parametrized constructor to Person, as the default, no-args constructor will not be implied anymore, but your Employee constructors would need to invoke it.

Now, if your Person class featured both a no-args and a String-parametrized constructor (with the same Employee implementation), your code would compile, and either invocation of Employee's constructors would still invoke Person's no-args constructor first.

Upvotes: 2

Related Questions