简体   繁体   中英

Calling methods from extended classes on array from abstract class

I am trying to call a certain method from a class that extendes an abstract class, on a array from the abstract superclass. Is there any possiblity to do that?

users[findUser(userName)].setVehicle(vehicles[counterVehicles])

if you know that the result of users[findUser(userName)] is always of certain type you can do this:

((ConcreteUser)users[findUser(userName)]).setVehicle(vehicles[counterVehicles])

Otherwise you'll have to test with instanceof certain type before making the call.

To avoid all this, best thing you can do is implement the visitor pattern. This is how could it be:

interface UserVisitor {
    public void visit(ConcreteUser1 user1);

    public void visit(ConcreteUser2 user2);
}


static class VehicleVisitor implements UserVisitor {

    private Vehicle vehicle;
    private Bus bus;

    VehicleVisitor(Vehicle vehicle, Bus bus) {
        this.vehicle = vehicle;
        this.bus = bus;
    }

    public void visit(ConcreteUser1 user1) {
        user1.setVehicle(vehicle);
    }

    public void visit(ConcreteUser2 user2) {
        user2.setBus(bus);
    }
}

static abstract class AbstractUser {
    public abstract void accept(VehicleVisitor visitor);
}

static class ConcreteUser1 extends AbstractUser {

    private Vehicle vehicle;

    public void accept(VehicleVisitor visitor) {
        visitor.visit(this);
    }

    public void setVehicle(Vehicle vehicle) {
        this.vehicle = vehicle;
    }

    public Vehicle getVehicle() {
        return vehicle;
    }
}

static class ConcreteUser2 extends AbstractUser {

    private Bus bus;

    public void accept(VehicleVisitor visitor) {
        visitor.visit(this);
    }

    public void setBus(Bus bus) {
        this.bus = bus;
    }

    public Bus getBus() {
        return bus;
    }
}

static class Vehicle {

    @Override
    public String toString() {
        return "CAR";
    }
}
static class Bus {

    @Override
    public String toString() {
        return "BUS";
    }
}

public static void main(String[] args) {
    List<AbstractUser> users = new ArrayList<AbstractUser>();
    ConcreteUser1 user1 = new ConcreteUser1();
    users.add(user1);
    ConcreteUser2 user2 = new ConcreteUser2();
    users.add(user2);

    for (AbstractUser user : users) {
        VehicleVisitor visitor = new VehicleVisitor(new Vehicle(), new Bus());
        user.accept(visitor);
    }

    System.out.println(user1.getVehicle());
    System.out.println(user2.getBus());
}

Now, I only have one visitor in the example to make it shorter, but you could have multiple types of visitors, each of them doing different things to different types of users.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM