Why is a throw necessary in this case?

class MyClass { private String str; public MyClass(String str){ this.str = str; } public int compare(Object o) { return str.compareTo(((MyClass)o).str); //line No.8 } } class Client { public static void main(String[] args) { MyClass m = new MyClass("abc"); MyClass n = new MyClass("bcd"); System.out.println(m.compare(n)); } } 

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 
+5
source share
2 answers

It comes down to what the compiler knows at compile time. At compile time, he knows that what will be passed to this method is of type Object . This means that it can guarantee methods associated with the Object class, but not methods like MyClass .

Since this compare method takes any argument of type Object or a subclass, you can pass anything to. What if I create a class MyOtherClass like this.

 public class MyOtherClass { public String notStr; } 

And I'm doing something like ..

 MyOtherClass myOtherClass = new MyOtherClass(); MyClass myClass = new MyClass(); myClass.compare(myOtherClass); 

Without translation, you have a situation where, at run time, it tries to access a field that is not there. The cast is done to ensure that the object is of the correct type or that it will fail before it tries to access this field.

As with

I work intensively with a language called Groovy. This is a language that essentially sits on top of Java, but it supports things like dynamic linking and free typing (this is what you are doing here). If you need this functionality, I would recommend checking out the documentation .

+8
source

o The compare type is Object . This means that the parameter can be an instance of MyClass , but it also could not. Object has no field called str (since it belongs to MyClass ), so there is no way to get that field from it, so the code cannot compile. However, if you added to MyClass , it will have a field named str, and it will be able to access it.

+1
source

All Articles