Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
This is just simple question in java inheritance.
Suppose I created a base class from a super class like

class Toyota extends Car{
String modelNumber;

public Toyota(String modelNumber)
{
this.modelNumber = modelNumber;

//rest of the member data should remain as the default value in the car class.
}

}
the Car class has its own constructor with the default value;


so if I am instantiating a Toyota class in another class then how do i create a new toyota class such that all the member data remain same as a parent class with extra data added as a model number;
does Toyota myCar = new Car() does that ?
is there a mechanism where even if I create a new class using new Toyota() instead of new Car() will inherit the default value for the new Toyota object.
Posted

1 solution

Toyota myCar = new Car()

You can't do that!
Because Toyota is derived from Car, it can and should contain information that a Car object doesn't. That info can't be "invented"! :laugh:

If you could do that, it would be like saying "An apple is a fruit, so all fruits are apples" which is patently nonsense!

What you need to say is
Car myCar = new Toyota()
because a Car could be a Toyota, or a Ford, or a Ferrari, or ...

And that gives you the Toyota constructor as well as the Car constructor.
 
Share this answer
 
Comments
xcelme 13-Sep-14 2:07am    
thanks that makes sense
OriginalGriff 13-Sep-14 3:22am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900