I'm preparing for a java exam. 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?
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(). Whereas, the superclass object reference o will only be able to call it's own methods and not those of the subclass? 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.
However, any method that you call on o that is defined on the String class will call the later version of the method. For example, o.toString() will return "hello", and not the descriptor that the Object.toString() normally returns. This is called polymorphism.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With