TurkuBasicOOPinJava / Week 6: Methods of OO Programming /11B. Calculate the Total Load of Trucks
KaiquanMah's picture
SubClass1 subClassVar1 = (SubClass1) superClassVar1;
f5d3ba7 verified
raw
history blame
2.49 kB
In the program, a class Car and its subclass Truck are defined.
Write a method
public static int totalLoad(ArrayList<Car> cars)
that receives a list of Truck objects as a parameter.
The method calculates and returns the total load of the trucks.
Note that the list type is Car, not Truck!
import java.util.Random;
import java.util.ArrayList;
public class Test{
public static void main(String[] args){
final Random r = new Random();
String[] brands = "Sisu Scania Volvo Ford Fiat Citroen".split(" ");
for(int test=1; test<=3; test++) {
System.out.println("Test " + test);
ArrayList<Car> cars = new ArrayList<>();
final int size = r.nextInt(4) + 3;
for (int i=0; i<size; i++) {
cars.add(new Truck(brands[r.nextInt(brands.length)], r.nextInt(20) + 5));
}
System.out.println("Cars:");
cars.stream().forEach(a -> System.out.println("" + a));
System.out.println("Total load: " + totalLoad(cars));
System.out.println("");
}
}
//add
// round 1 - NO
// public static int totalLoad(ArrayList<Car> cars) {
// int totalLoad = 0;
// for (Truck truck : cars) {
// totalLoad += truck.getLoad();
// }
// return totalLoad;
// }
// round 2 - YES
public static int totalLoad(ArrayList<Car> cars) {
int totalLoad = 0;
for (Car car : cars) {
// explicit type casting
Truck truck = (Truck) car;
totalLoad += truck.getLoad();
}
return totalLoad;
}
}
class Car {
protected String brand;
public Car(String brand) {
this.brand = brand;
}
public String getBrand() {
return brand;
}
}
class Truck extends Car {
private int load;
public Truck(String brand, int load) {
super(brand);
this.load = load;
}
public int getLoad() {
return load;
}
public String toString() {
return brand + ", load: " + load;
}
}
Test 1
Cars:
Sisu, load: 5
Volvo, load: 24
Sisu, load: 23
Total load: 52
Test 2
Cars:
Fiat, load: 9
Fiat, load: 10
Scania, load: 13
Ford, load: 16
Total load: 48
Test 3
Cars:
Volvo, load: 18
Ford, load: 22
Scania, load: 20
Sisu, load: 20
Volvo, load: 7
Sisu, load: 21
Total load: 108