简体   繁体   中英

Are reference objects with different types any different in Java?

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?

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");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM