Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Questions about object superclasses and casting

Tags:

java

oop

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.

like image 881
M_x_r Avatar asked Mar 15 '26 05:03

M_x_r


1 Answers

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.

like image 68
Rafael Avatar answered Mar 17 '26 02:03

Rafael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!