Design a BigTruck java class that extends the Truck class. The BigTruck class sh
ID: 3670062 • Letter: D
Question
Design a BigTruck java class that extends the Truck class. The BigTruck class should have the following members: 1. A field for the load capacity in tons (an int). 2. A constructor and appropriate accessors and mutators. 3. A toString method that overrides the toString method in the base class. The BigTruck class’s toString method should display only the truck’s name and the truck’s load capacity. Demonstrate the classes in a program that has a Truck array. Assign 2 Truck objects and 3 BigTruck objects to the array elements. The JAVA program should then step through the array, calling each object’s toString method. The output should display 5 trucks and each truck has the name and its load capacity.
Explanation / Answer
public class Truck {
private String name;
public Truck(String name) {
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Truck [ Name: "+name+" ]";
}
}
class BigTruck extends Truck{
private int load;
public BigTruck(String name,int load) {
super(name);
this.load = load;
}
public int getLoad() {
return load;
}
public void setLoad(int load) {
this.load = load;
}
@Override
public String toString() {
return "BigTruck [ Name: "+getName()+", Load: "+load+" ]";
}
}
class TestTruck{
public static void main(String[] args) {
Truck[] trucks = {new Truck("TATA"),new Truck("Motor"),new BigTruck("Honda", 30),
new BigTruck("SPice", 70)};
for(Truck t: trucks){
System.out.println(t);
}
}
}