0

Hi ,I have super class vehicle,truck extends vehicle,and I created array in test class full with objects from vehicle and truck,how can I call method from vehicle,is this the way
(truck)object1[1].getMethod()

Edited by kukuruku: n/a

3
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by jwenting
0

Hi ,I have super class vehicle,truck extends vehicle,and I created array in test class full with objects from vehicle and truck,how can I call method from vehicle,is this the way
(truck)object1[1].getMethod()

If you want to use the method from the vehicle class then cast the object as a vehicle:

((vehicle)object1[1]).getMethod();

Notice the extra set of parentheses there; without them you'll get a compile error, as Java will believe that you want to run getMethod() and then convert the result into a vehicle.

0

Thanks
vehicle is the super class,and truck is the child
getLoadCap is in truck class

public static void main(String[] args) {
		
		Vehicle data[]=new Vehicle[4];
		Vehicle vehObj=new Vehicle("Lamborgini",8);
		data[0]=vehObj;
		Vehicle vehObj1=new Vehicle();
		data[1]=vehObj1;
		Truck trObj=new Truck("Ford",4,1111,111);
		data[2]=trObj;
		Truck trObj1=new Truck();
		data[3]=trObj1;
		for(int i=0;i<4;i++){
			data[i].print();
		}
        data[2].getLoadCap();//here is the problem
       
	}
0
data[2].getLoadCap();

should be

((Truck)data[2]).getLoadCap();

as already explained.

And of course ideally you'd handle errors doing the casting.

Edited by jwenting: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.