class MyClass { private String str; public MyClass(String str){ this.str = str; } public int compare(Object o) { return str.compareTo(((MyClass)o).str);
Why is listing (MyClass)o on line 8 necessary in this code snippet, even though the client calls the compare method with arguments that are instances of the MyClass class?
When I change the compare method in the MyClass class, as shown below:
public int compare(Object o) { System.out.println(o.getClass()); System.out.println(((MyClass)o).getClass()); return str.compareTo(((MyClass)o).str); }
Then the client will produce the following result:
class MyClass class MyClass
Thus, I do not understand why it is required to throw higher, and why I cannot just like that (without adding to MyClass):
public int compare(Object o) { return str.compareTo(o.str); }
Because when I do this, I get a compile-time error:
str cannot be resolved or is not a field
source share