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

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

java - call subclass methods by superclass reference

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...