Reputation: 8931
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 () {...}
}
Upvotes: 1
Views: 3694
Reputation: 206796
Ofcourse you can make a List
that contains Vehicle
objects:
List<Vehicle> list = new LinkedList<Vehicle>();
When you do System.out.println(list.get(2));
then it will get the Vehicle
object at index 2 and call toString()
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
, Truck
or Car
(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 of list.get(...)
.
You can call any method that's declared in class Vehicle
(or superclasses - toString()
is declared in class Object
) without casting, and the method appropriate for the specific object (Bus
, Truck
or Car
) will be called - that's what polymorphism is all about.
Upvotes: 3
Reputation: 308753
Yes, that'll work without type casting as long as the differences are private. That'll change the moment you add a method to one that doesn't appear in the interface.
Upvotes: 3