I want to make a list of instances of classes. The instances belong to different classes, though they all belong to the same super class. Is this something I should avoid? Or is this fine. Any suggestions on how to best implement this, would be great.
For example, I have a super class Vehicle and two other classes, Bike and Car as classes that extend Vehicle. For convenience I want to store all Vehicles in one array/list as I want to display all vehicles using a simple loop.
Hope I am not seriously overlooking something and this doesn't turn out to be too trivial (or just bad practice).
It surely is a legal move:
public class Main {
public static void main(String[] args) {
List<Vehicle> list=new ArrayList<>();
list.add(new Car());
list.add(new Bike());
}
}
class Vehicle{}
class Car extends Vehicle{}
class Bike extends Vehicle{}
but it all depends on what you're trying to achieve.