通过超类引用调用子类方法 [英] call subclass methods by superclass reference

查看:56
本文介绍了通过超类引用调用子类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

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

为什么不能在第(5)行中调用 length();在第(6)行中将为哪个类调用 equals()?

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

推荐答案

您不能这样做,因为子类的方法不在您的超类中.在这种情况下,尽管String是Object的子类,因为在java.lang.Object类中未声明length(),但无法在其实例上调用length.

you cannot do that, as subclass's methods are not in your super class. In this case, though String is a subclass of Object as length() is not declared in java.lang.Object class its no possible to call length on its instance.

equals()方法在字符串类中被覆盖,因此将调用Strings的equals()

equals() method however is overriden in string class, thus Strings's equals() will be invoked

这篇关于通过超类引用调用子类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆