Java – when an object is an instance of a base class, call the correct method for the object
•
Java
I have the following examples in Java:
public abstract class Vehicle {
private final String name;
private final String make;
public Vehicle(final String name,final String make) {
this.make = make;
this.name = name;
}
}
public final class Car extends Vehicle {
public Car(final String name,final String make) {
super(name,make);
}
}
public final class Truck extends Vehicle {
final Integer grossVehicleWeight;
public Truck(final String name,final String make,final Integer gvw) {
super(name,make);
this.grossVehicleWeight = gvw;
}
I want to use the car to do some work, and the work does not depend on the subclass of the vehicle Therefore, I have a method in another class, as follows:
public void doStuff(public final Vehicle vehicle) {
//do stuff here
//then insert it into my database:
insertVehicle(vehicle);
}
However, I want to do different things in insertvehicle, so I override this method for each subclass:
public void insertVehicle(Car car) { //do stuff for a car }
public void insertVehicle(Truck truck) { //do stuff for a truck }
In my dostuff method, I can use instanceof to determine the vehicle category (car or truck), then project the vehicle to this class and call the insertvehicle method, as shown below:
public void doStuff(public final Vehicle vehicle) {
//do stuff here
//then insert it into my database:
if (vehicle instanceof Car) {
insertVehicle((Car) vehicle);
} else {
insertVehicle((truck) vehicle);
}
}
However, I have read that using instanceof is not the best way one
How can I best redo this so that I don't have to use instanceof?
Solution
You can use visitor mode:
public interface VehicleVisitor {
public void visit(Car car);
public void visit(Truck truck);
}
public class Car extends Vehicle {
@Override
public void insert(VehicleVisitor vehicleVisitor) {
vehicleVisitor.visit(this);
}
}
public class Truck extends Vehicle {
@Override
public void insert(VehicleVisitor vehicleVisitor) {
vehicleVisitor.visit(this);
}
}
public abstract class Vehicle {
public abstract void insert(VehicleVisitor vehicleVisitor);
}
public class VehicleVisitorImpl implements VehicleVisitor {
@Override
public void visit(Car car) {
System.out.println("insert car");
}
@Override
public void visit(Truck truck) {
System.out.println("insert truck");
}
}
public class Main {
public static void main(String[] args) {
Vehicle vehicle = new Car();
// finally the agnostic call
vehicle.insert(new VehicleVisitorImpl());
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
