manuka_m manuka_m - 20 days ago 5
Java Question

How to access SubClass methods from an array of Superclass?

I have a super class called Vehicle, have three sub classes called van,car and motorbike. Each time the user select one of those sub classes it should create an object of that particular subclass and store it in the array of superclass. I just want to access the methods of the subclass from that array. Can i do that?

Answer

if you know which one is which, you can:

    Vehicle[] vehicles; // your array

((Car)vehicles[3]).openTrunk(); // if you know vehicles[3] is a car you can do this
Comments