My problem: I have 2 objects and want to use an overloaded .equals() to compare the name and color attribute of the two objects being compared and if they are the same, it will return true.
I have two objects. car1 and car2
GameCar car1 = new GameCar ("MyBuddy", "Red", 19);
GameCar car2 = new GameCar();
The GameCar class has 3 private member variables:
private String name;
private String color;
private int position;
Here are the two constructors for GameCar -
GameCar()
{
name = null;
color = null;
position = 0;
}
GameCar(String n, String c, int p)
{
name = n;
color = c;
position = p;
}
In order for car2 to get its information, I have this:
car2.getCarInfo();
Definition of getCarInfo() -
public void getCarInfo()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the car name: ");
name = keyboard.next();
System.out.print("Enter the color: ");
color = keyboard.next();
System.out.print("Enter the starting position: ");
position = keyboard.nextInt();
}
And now here's the equals() overloaded function -
public boolean equals(GameCar car)
{
if (name == car.name) return true;
return false;
}
Here is where I'm using the equals() -
System.out.println("Same cars? " + car1.equals(car2));
For some reason, the equals() function, even if I set the car2.name and car1.name to be exactly the same prior to going into the equals(), it still returns false.
However--- If I set name="something" and car.name="something" in the overloaded equals(), then it will work.