ravikiran
ravikiran

Reputation: 43

constructor in inheritance in java

public class Conininher {
      public static void main(String[] args) {
        Ba obj1=new Ba();
      }
}

class Aa{
    public Aa(){
        this(10);
        System.out.println("hello");
    }
    public Aa(int x){
        System.out.println("hw r u");
    }
}

class Ba extends Aa{
    public Ba(){
        this(5);
        System.out.println("hii");
    }
    public Ba(int x){
        System.out.println("bye");
    }
}

Why isn't the this(10) in Aa not working? when the object of class Ba is created, at first the default constructor of Ba is called which in turn calls the default constructor of Aa, which calls the parameterised constructor of Aa. so, I was expecting the output to be hello, hw r u, hii , bye.

Upvotes: 1

Views: 114

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201527

If the first line of a constructor call isn't a super() or this(), then a super() is inserted. For your desired output, you need something like

class Aa {
    public Aa() {
        System.out.println("hello");
    }

    public Aa(int x) {
        this();
        System.out.println("hw r u");
    }
}

class Ba extends Aa {
    public Ba() {
        this(5);
        System.out.println("bye");
    }

    public Ba(int x) {
        super(x);
        System.out.println("hii");
    }
}

Which I ran and got (as requested)

hello
hw r u
hii
bye

Upvotes: 1

Eran
Eran

Reputation: 394126

Why did you expect "hello" to be printed before "hw r u"?

public Aa()
{
    this(10);
    System.out.println("hello");
}

calls

public Aa(int x)
{
    System.out.println("hw r u");
}

so "hw r u" is printed first, and only afterwards "hello" is printed.

Similarly, "bye" is printed before "hii", since

public Ba()
{
    this(5);
    System.out.println("hii");

}

calls

public Ba(int x)
{
    System.out.println("bye");
}

which prints "bye", and only after it returns, "hii" is printed.

To summarize:

Ba obj1=new Ba();

calls

public Ba()

which calls

public Ba(int x)

which calls

public Aa()

which calls

public Aa(int x)

which prints "hw r u"

then public Aa() prints "hello"

then public Ba(int x) prints "bye"

finally public Ba() prints "hii"

Upvotes: 3

Related Questions