1

Why does a subclass not able to use just his own default constructor? When Bike extends Vehicle class, then why Bike is using Vehicle's constructor for creating a bike object?

That seems okay to use parent's class constructor when a bike object is having some more additional members which doesn't exist in parent class then using the super class to decrease writing additional duplicate code to initialize. It looks okay.(Might be I am completely wrong).

public class Vehicle {

    Vehicle()
    {

        System.out.println("Vehicle is created");

    }
}

public class Bike extends Vehicle {

    public static void main(String[] args){

        Bike HondaBike = new Bike();    
    }
}

Output: Vehicle is created
Oguz
  • 1,867
  • 1
  • 17
  • 24
LearnJava
  • 372
  • 1
  • 4
  • 16
  • You can check, https://stackoverflow.com/questions/2967662/any-way-to-not-call-superclass-constructor-in-java. BTW: There is no way to not calling parent's constructor. Child 's classes should contain the parent's constructor and may extend with its constructor if it's needed. – Oguz Aug 20 '17 at 10:59
  • That's the way java works. – Heri Aug 20 '17 at 11:00

1 Answers1

1

new Bike() invokes the parameter-less constructor of class Bike, which invokes the parameter-less constructor of its super class Vehicle, but since you didn't write a parameter-less constructor for class Bike, the compiler generated one with an empty body. Therefore it appears to you that only Vehicle's constructor is executed.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • @Earn..That's my question. Why super class's constructor needs to be invoked ? – LearnJava Aug 20 '17 at 10:45
  • @LearnJava Because in order to initialize an instance of a class you have to first initialize all the properties that belong to the super classes of that class, which requires executing the constructors of all these super classes. – Eran Aug 20 '17 at 10:47
  • @Earn, Do you think so "son needs to use father's constructor for creating his own son" ? – LearnJava Aug 20 '17 at 10:49
  • @LearnJava The "son" object inherits properties from the "father" class. These properties must be initialized. The "father" constructor does the initialization. Therefore the "father" constructor must be executed a part of the initialization of the "son" object. – Eran Aug 20 '17 at 10:52
  • @Earn, So you mean to say for the common properties and to initialise them, always superclass's constructor will be used ? – LearnJava Aug 20 '17 at 10:57
  • @Earn, Do JVM keeps separate copy of common properties of parent and child class ? – LearnJava Aug 20 '17 at 11:03