Search code examples
javaobject

Operator '==' cannot be applied...(java)


I'm, having a little problem understanding why I get this compiler error. This was just a way for me to understand how all reference type inherit from Object class, but I'm more lost than ever :(

import static java.lang.System.out;

public class InheritObject {

    public static void main(String[] args) {
        new InheritObject().program();
    }

    void program() {
        MyOwnClass m = new MyOwnClass();

        out.println(m.toString());
        out.println(m.getClass());   // Get class used to create this object
        out.println(m.equals("abc"));  // m == "abc" not allowed, but equals is!
        out.println(m=="abd");      // ... and default equals() uses == ?!
        out.println(m.equals(5));
        out.println(m.hashCode());
        // Etc.

    }

    class MyOwnClass{
        // No methods here!!!
    }
}


Solution

  • The method equals exists on all Object instances and permits any other Object (or null) to be passed. m.equals("abc") is therefore okay; it meets the (very loose) requirements of equals.

    This is allowed because one could write an equals method that indeed does allow an MyOwnClass instance to be equal to a String instance. (It's probably not a good idea, but something technically valid.)

    == is different. It has a very specific meaning when dealing with reference types. It returns true if and only if the two arguments are the exact same instance; false otherwise.

    However, in this case, when comparing an MyOwnClass and a String, the compiler knows that that comparison can never ever be true since the two provably don't inherit from each other. There is no situation where this comparison would make sense or even be useful; the developer must have made a mistake.

    If you still want to make this comparison nonetheless, you can cast one or both of the arguments to Object:

    out.println(m == (Object) "abd");
    

    The comparison is now between a MyOwnClass and an Object. Since MyOwnClass inherits from an Object, a someMyOwnClass == someObject could sometimes be true, so the comparison is permitted.