-2

I want to Call the Parent Method in Java With A child Reference

Truck tv=new Vehicle();

Truck is the child class and Vehicle is a parent Class should i have to use type casting?

geoand
  • 60,071
  • 24
  • 172
  • 190
Tayyab Vohra
  • 1,512
  • 3
  • 22
  • 49
  • It's not possible from outside the subclass (and there are good reasons for it). – Marcin Łoś Apr 26 '14 at 13:30
  • possible duplicate of [Can java call parent overridden method in other objects but not subtype?](http://stackoverflow.com/questions/1032847/can-java-call-parent-overridden-method-in-other-objects-but-not-subtype) – Artur Malinowski Apr 26 '14 at 13:44
  • 1
    `Vehicle tv=new Vehicle();` is legal and `Vehicle tv=new Truck();` is legal. But what you've written isn't because a Vehicle isn't a Truck (even though a Truck is a vehicle) – Richard Tingle Apr 26 '14 at 13:44
  • Is the parent method overriden by the child? – Richard Tingle Apr 26 '14 at 13:45

2 Answers2

2

You cannot have a reference variable of base class pointing to the object instantiated of the derived class, better have a reference of base class pointing to its own class i.e,

    Truck tv = new Truck();

Thanks, Balaji.

balaji
  • 774
  • 1
  • 16
  • 42
1

What you are doing will not compile since Truck is a sublass and you are instantiating a superclass.

You need to call Truck's constructor like this:

Truck tv=new Truck();

Using that, all methods that are present in Vehicle can be called on the Truck reference

geoand
  • 60,071
  • 24
  • 172
  • 190