0

Consider this code :

public class Vehicle{
    private int pos_x;
    private int pos_y;

    public void update(float delta){
        move(delta); // function move() isn't shown here but modifies pos_x and pos_y
    }
}

public class Car extends Vehicle{
    private int speed = 10;

    @Override
    public void update(float delta){
        super.update(delta * speed);
    }
}

public class Tank extends Vehicle{
    private int speed = 3;
    private int munitions = 100;

    @Override
    public void update(float delta){
        super.update(delta * speed);
    }

    public void shoot(){
        // Do something
    }
}

public void main(String[] args){
    List<Vehicle> vehicles = new ArrayList<Vehicle>();
    vehicles.add(new Car());
    vehicles.add(new Tank());

    while(true){
        float delta = getElapsedTimeSinceLastLoop(); // not shown
        for(Vehicle v : vehicles){
            v.update(delta);
            if(playerIsHoldingDownShootButton())((Tank)v).shoot();
        }
        sleep(); // not shown
    }
}

If i don't try to cast v to Tank, i can't access the shoot() function. If i try to cast v to Tank, i get an error because vehicles list contains a Car, which cannot be cast to a Tank. The only way i could avoid the error is by testing if(v instanceof Tank) and then cast to Tank.

But what if i have a lot of vehicle types with their own different functions?

edit : Thanks to @ScaryWombat, i rewrote the question a bit to get closer to my actual problem.

aTom
  • 406
  • 6
  • 17

1 Answers1

1

In the main method, just call update() on all vehicles. Let the Tank determine by itself whether to shoot in its own update method.

Raimund Krämer
  • 1,255
  • 1
  • 11
  • 29