1

Why default constructor(same class) is not getting called while calling the default constructor but the default constructor of parent class is getting called - Why?

class A{
    A(){
        System.out.println("A()");
    }
}

class B extends A{
    B(){
        System.out.println("B()");
    }
}

class C extends B{
    C(){
        System.out.println("C()");
    }
    C(int i){
        System.out.println("<------>"+i);
    }
}
public class sample {
    public static void main(String[] args) {
        C c = new C(8);

    }
}

Output:

A()
B()
<------>8
Dante May Code
  • 11,177
  • 9
  • 49
  • 81
bharanitharan
  • 2,539
  • 5
  • 32
  • 30
  • 3
    Technically that's not a default constructor. In Java you get a synthetic default constructor supplied if there is no constructor in the source. A constructor with zero parameters is referred to as a *no-args* constructor. This is different from C++ where the default constructor is called by default in various situations. (The only(?) case in the Java language where a no-args constructor will be called implicitly is where a subclass constructor does not call a `this(...)` or `super(...)` explicitly.) – Tom Hawtin - tackline May 19 '11 at 13:12

4 Answers4

10

This is how the language works: only one constructor is called per class, unless you specifically invoke one constructor from another (like so: How do I call one constructor from another in Java?).

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
4

It's Java's rule. If you want your behaviour you must use this() as first instruction in C(int).

cadrian
  • 7,332
  • 2
  • 33
  • 42
4

as said before it's standard behavior of java if you want some code to be always called on construction of an object you can use an initializer

class A{
    {
       System.out.println("A()");
    }
    A(){

    }
}
ratchet freak
  • 47,288
  • 5
  • 68
  • 106
4

Based on your class declaration for class 'C', you are overloading the constructors and thus when you create a new 'C' object and pass in an integer with the following code:

C c = new C(8);

You are calling the constructor

C(int i){
    System.out.println("<------>"+i);
}

instead of the constructor

C(){
    System.out.println("C()");
}

therefore it doesn't print out "C()". Overloading constructors/functions depends on the type and number of parameters being passed in. On top of that, only 1 constructor gets called for each object being created.

David Lin
  • 631
  • 8
  • 10