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()

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.

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
       
	}
data[2].getLoadCap();

should be

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

as already explained.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.