Polymorphism in Java with the toString and Equals Method makes no sense to me?
Asked Answered
B

1

5

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.

Bangtail answered 28/4, 2020 at 6:29 Comment(2)
just so you know: this -> System.out.println(maggie.toString()); is the same as this -> System.out.println(maggie);Gebhardt
Much appreciated @EmaadShamsi.Dramaturgy
Y
7

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.

Yuzik answered 28/4, 2020 at 6:35 Comment(1)
Wow, I totally missed that. THANK YOU!!Bangtail

© 2022 - 2024 — McMap. All rights reserved.