bharanitharan
bharanitharan

Reputation: 2629

Default constructor not getting called

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

Upvotes: 1

Views: 9064

Answers (4)

David Lin
David Lin

Reputation: 631

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.

Upvotes: 4

ratchet freak
ratchet freak

Reputation: 48206

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(){

    }
}

Upvotes: 4

cadrian
cadrian

Reputation: 7376

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

Upvotes: 4

NPE
NPE

Reputation: 500495

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?).

Upvotes: 10

Related Questions