I'm currently practicing with object oriented programming, and I've stumbled across on using Override in my program. Over here I want to override the equals method in the class Car and use ONLY plateNumber to determine whether a Car is the same (equal).
Although it is giving the desired output, it isn't using boolean result And I had to use CharSequence in order to compare it. How can I use string compare in this case?
class Car {
private String make;
private String model;
private String plateNumber;
private int horsePower;
public Car(String make, String model, String plateNumber, int horsePower) {
this.make = make;
this.model = model;
this.plateNumber = plateNumber;
this.horsePower = horsePower;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getPlateNumber() {
return plateNumber;
}
public void setPlateNumber(String plateNumber) {
this.plateNumber = plateNumber;
}
public int getHorsePower() {
return horsePower;
}
public void setHorsePower(int horsePower) {
this.horsePower = horsePower;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Car))
return false;
Car that = (Car) o;
return CharSequence.compare(plateNumber, that.plateNumber) == 0;
}
}
class Main {
public static void main(String args[]) {
Car car1 = new Car("Toyota", "RAV4", "ABC-123", 104);
Car car2 = new Car("Renault", "Megane", "DEF-789", 132);
Car car3 = new Car("Ford", "Mondeo", "GHI-012", 132);
Car car4 = new Car("Mercedes", "C180", "ABC-123", 144);
if (car1.equals(car4)) {
System.out.println("Equal ");
} else {
System.out.println("Not Equal ");
}
boolean result = car1.equals(car4);// this should return true because the plateNumbers are the same
result = car1.equals(car2); // this should return false because the plateNumbers don't match
}
}