Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have code like this:

String stringRef = new String("Java");                    // (1)

System.out.println("(2): " + stringRef.getClass());       // (2)
System.out.println("(3): " + stringRef.length());         // (3)

Object objRef = stringRef;                                // (4)

// System.out.println("(5): " + objRef.length());            // (5) Not OK.
System.out.println("(6): " + objRef.equals("Java")); 

Why can I not call length() in line (5); and for which class will equals() be called in line (6)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
268 views
Welcome To Ask or Share your Answers For Others

1 Answer

equals is declared on Object so you can call it; length isn't. The compiler will not try to determine what exactly object type is referred to by objRef; it works only with the knowledge that it is an Object.

The Java compiler statically resolves the signature of the method to call, based on the static type of the expression to the left of the dot operator. The concept of polymorphism and dynamic dispatch applies only to the resolution of which overriding method to call.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...