Reputation: 112
Given the following code:
class Kitten {
private String name = "";
public Kitten(String name) {
name = name;
}
public String toString() {
return "Kitten: " + name;
}
public boolean equals(Object other) {
if (this == other) return true;
if (null == other) return false;
if (!(other instanceof Kitten)) return false;
Kitten that = (Kitten) other;
return this.name.equals(that.name);
}
}
//Assume that the Following lines have already been executed
Object maggie = new Kitten("Maggie");
Object fiona = new Kitten("Fiona");
Object fiona2 = new Kitten("Fiona");
Apparently, when you run the lines of code:
> System.out.println(maggie.toString());
>
> System.out.println(fiona.equals(fiona2));
>
> System.out.println(fiona.equals(maggie));
>
The terminal will print out the following:
>Kitten:
>
>true
>
>true
WHY does the toString method use the Kitten class's overridden method but somehow not use the name value stored in maggie?
Also how is it possible that fiona.equals(maggie) is true?
If there is a resource that I can use to read about and teach myself the intricacies of polymorphism for future reference, I would appreciate that too.
Upvotes: 5
Views: 214
Reputation: 97150
The problem is in the constructor:
public Kitten(String name) {
name = name;
}
This just assigns the name
parameter to itself, which is a no-op.
To assign the value of the name
parameter to the name
property, you would need to do:
public Kitten(String name) {
this.name = name;
}
After changing that, your toString()
and equals()
methods will behave as expected.
Upvotes: 7