I am trying to create a simple GUI with Java. I have an Arraylist executed like this:

private List<Vehicle> vehicles = new Arraylist<>();

Im trying to pass in a subclass object with more parameters than the superclass.

I have tried Casting it and overriding toString method but nothing seemed to work

My supeprclass:

public abstract class Vehicle {
    private int speed; 
    public Vehicle (int speed) {
        this.speed = speed;

My subclasses:

public class Car extends Vehicle {
    private int gear; 
    public Car (int speed, int gear) {
        this.gear = gear;

public class Bike extends Vehicle {
    public Bike (int speed) {

I instantiate in the class where i initialize the Arraylist

Car car = new Car (100, 5);

i can initialize Car without problems. Parameters get sent, but the result im getting is only an instance of the superclass. Where am i going wrong?

1 Answers

Abra On Best Solutions

It is a well-known aspect of java generics that List<Car> is not a subclass of List<Vehicle>. That's why there are constructs such as List<? extends Vehicle> and List<? super Car>. There are many online resources that show how to handle your situation. For example Generics, Inheritance and Subtypes