简体   繁体   English

关于对象超类和转换的问题

[英]Questions about object superclasses and casting

I'm preparing for a java exam. 我正在准备java考试。 I came across the following question 我遇到了以下问题

String s = new String ("hello");
Object o = (object) s;

Since o and s are both references that point to the same object, is there any difference in accessing the object through the reference s over the reference o ? 由于os是指向同一个对象的引用二者,是在有通过参考访问对象的任何差异s超过参考o

Would I be right in saying that all objects (like the one being reference by s) are subclasses of Object in Java and as such using the reference s you will be able to call the methods known by the superclass Object like clone() and the methods known by String like length() . 我是否正确地说所有对象(如s引用的Object )都是Java中的Object子类,因此使用引用s您将能够调用超类Object已知的方法,如clone()String所知的方法,如length() Whereas, the superclass object reference o will only be able to call it's own methods and not those of the subclass? 然而,超类对象引用o只能调用它自己的方法而不能调用子类的方法吗? Thanks. 谢谢。

The difference is that by using o you will not be able to call string specific methods unless you cast it back to String. 不同之处在于,通过使用o,除非将其强制转换为String,否则无法调用特定于字符串的方法。

However, any method that you call on o that is defined on the String class will call the later version of the method. 但是,在String类上定义的任何调用o的方法都将调用该方法的更高版本。 For example, o.toString() will return "hello", and not the descriptor that the Object.toString() normally returns. 例如,o.toString()将返回“hello”,而不是Object.toString()通常返回的描述符。 This is called polymorphism. 这称为多态性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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