I have a super class Vehicle and three classes that extend on it: Bus, Car and Truck. I want to have a linked list that will contain vehicles of different types, I use
list = new LinkedList<Vehicle>()
and it seems to work when I use System.out.println(list.get(2)), but I don’t understand why? I’ve added as an experiment toString() function to Vehicle class which is deferent, but it still uses the extended classe’s toString(). When will it use the father’s function, and when it’s sons?
All the different classes have the same functions, but different private variables.
the classes are:
public class Vehicle {
protected String maker;
protected int year;
private int fuel; //0 1 2 3 4
public Vehicle (String maker, int year) {
this.maker = maker;
this.year = year;
this.fuel = 0;
}
public void drive () {...}
public void fill () {...}
}
Bus:
public class Bus extends Vehicle{
private int sits;
public Bus (String maker, int year, int sits) {
super (maker, year);
this.sits = sits;
}
public String toString () {...}
}
Truck:
public class Truck extends Vehicle{
private int weight;
public Truck (String maker, int year, int weight) {
super (maker, year);
this.weight = weight;
}
public String toString () {...}
}
Car:
public class Car extends Vehicle{
private float volume;
public Car (String maker, int year, float volume) {
super (maker, year);
this.volume = volume;
}
public String toString () {...}
}
Ofcourse you can make a
Listthat containsVehicleobjects:When you do
System.out.println(list.get(2));then it will get theVehicleobject at index 2 and calltoString()on it, and then this string is printed to the console (you can ofcourse easily try that out yourself).Note that if you want to call a method that is specific to a
Bus,TruckorCar(i.e., defined in one of those classes and not in a superclass), then there is no way to do that without casting the result oflist.get(...).You can call any method that’s declared in class
Vehicle(or superclasses –toString()is declared in classObject) without casting, and the method appropriate for the specific object (Bus,TruckorCar) will be called – that’s what polymorphism is all about.