我有一个超类Vehicle
和三个在其上扩展的类Bus
:Car
和Truck
. 我想要一个包含不同类型车辆的链接列表,我使用
list = new LinkedList<Vehicle>()
当我使用它时它似乎工作System.out.println(list.get(2))
,但我不明白为什么?我已将实验toString()
功能添加到不同的Vehicle
类中,但它仍然使用扩展类的toString()
. 什么时候使用父亲的功能,什么时候使用儿子的功能?
所有不同的类都具有相同的功能,但私有变量不同。
课程是:
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 () {...}
}
公共汽车:
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 () {...}
}
卡车:
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 () {...}
}
车:
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 () {...}
}