constructors in java

public class A {
public A() {
    System.out.println("a1");
}
public A(int x) {
    System.out.println("a2");

}}

public class B extends A {
public B() {
    super(5);
    System.out.println("b1");
}
public B(int x) {
    this();
    System.out.println("b2");
}
public B(int x, int y) {
    super(x);
    System.out.println("b3");
}}

I don’t understand why the default constructure of A is not applied when I run B b= new B();

B extends A, so First we call the constrcture of A that supposed to print “a1”, and then we call the the second constructure of A which prints “a2” and B() prints “b1”, but when I run it, it prints only “a2,b1”, so obviously A() wan’t applied at the beginning- why?

Answer

B extends A, so First we call the constrcture of A that supposed to print “a1”

This statement is incorrect. In class B your no arguments constructor

public B() {
    super(5);
    System.out.println("b1");
}

calls the constructor of the superclass (class A) which takes an int parameter.

public A(int x) {
    System.out.println("a2");
}

You never make a call to super() so the constructor that prints “a1” will not be called when you call any of B’s constructors

Calling a super constructor must be the first line of a constructor. If you wish to call the no argument constructor of a superclass (in this case, the one that prints “a1”), you would write…

public B() {
    super();
    System.out.println("b1");
}

If you do not specify calling a super constructor, then java will automatically put in a call to the no argument super constructor.

Leave a Reply

Your email address will not be published. Required fields are marked *