I have three classes. Class Vehicle, class Truck and class Car. Class Truck and class Car extend from class Vehicle. class Vehicle has three fields:
protected String model;
protected int year;
protected int price;
Class Truck has one field:
private String color;
and the method:
public String getColor(){
return color;
}
Class Car has one field:
private boolean rusty;
I have an array called vehicles(which stores 30 objects) to store Truck objects as well as Car objects.
I have another class called VehicleDealer in which I have created the array and different methods including:
int VEHICLE_COUNTER= 0;
public void addTruck(String m, int y, int p,String c){
Vehicle truck1 = new Truck( m, y, p, c);
vehicles[VEHICLE_COUNTER] = truck1;
VEHICLE_COUNTER = VEHICLE_COUNTER + 1;
}
public void addCar(String m, int y, int p,boolean r){
Vehicle car1 = new Car( m, y, p, r);
vehicles[VEHICLE_COUNTER] = car1;
VEHICLE_COUNTER = VEHICLE_COUNTER + 1;
}
public String printAllVehiclesOfColor(String c){
String s = "";
for (int i=0; i < VEHICLE_COUNTER; i++) {
String x = vehicles[i].getColor();
if(x == c){
s += vehicles[i].printThis(i) + "\n";
}
}
return s;
}
I have a main class which looks like this:
public class TestDealer{
public static void main(String[] args){
VehicleDealer dealer = new VehicleDealer();
dealer.addTruck("Ford", 2012, 55000, "Green");
dealer.addTruck("Ford", 2001, 23050, "Black");
dealer.addCar("BMW", 2010, 17000, false);
System.out.println(dealer.printAllVehiclesOfColor("Green"));
}
}
In this line of code I get an error which says that cannot find symbol for getColor().
for (int i=0; i < VEHICLE_COUNTER; i++) {
String x = vehicles[i].getColor();<---------------
if(x == c){
s += vehicles[i].printThis(i) + "\n";
}
}
So I put the getColor() method in class Vehicle and then tried to compile the code but it did not work as I have not declared a color field in class Car. My question requires me to declare the color field in class Truck only.
What is wrong with my code? I am new to Java. Any help is appreciated. Thank you!!