Reputation: 5563
When saying:
String str = "hello";
Object obj = str;
System.out.println(str==obj);
The result is true, because it points to the same objects in memory, which makes sense. But if I say:
obj.indexOf("h");
Or any subclass method, I get "cannot find symbol". They're still pointing to the same object, so what's going on during compile-time that makes reference objects of different types different from each other?
Upvotes: 1
Views: 41
Reputation: 13858
Apples and Pears.
The identity check == is performed at runtime. And valid and fine.
The construct obj.indexOf...
is a compile time error as class Object just does not have a method indexOf
If you tell the compiler (by means of casting) that obj contains a String, you can get valid code
((String)obj).indexOf("h");
Will compile again
Upvotes: 0
Reputation: 308753
The Object
type reference only knows about methods that are part of its public interface.
You have to cast if you know that Object
reference is a String
type:
int index = ((String) obj).indexOf("h");
Upvotes: 3