Note that there are some explanatory texts on larger screens.

plurals
  1. POCasting reference variable in Java
    primarykey
    data
    text
    <p>I have something unclear concerning casting reference variable in Java.</p> <p>I have two classes A and B. A is the super class of B. If I have the two objects, and then the print statement:</p> <pre><code>A a = new A(); //superclass B b = new B(); //subclass System.out.println ((A)b); </code></pre> <p>then what exactly is happening when the println method is executed?</p> <p>I know that because B is a subclass of A, I am allowed to make the following cast:</p> <pre><code>A a2 = (A)b; </code></pre> <p>I also know that when println takes a reference variable as argument, then the toString() method of the class, which has created the object-argument, is invoked (implicitly). This is so, because the method println() is looking for an argument of type String, and the toString() method represent the object as a string. And even if we don't write toString(), the method is invoked - implicitly. So, the following two statements are equivalent:</p> <pre><code>System.out.println (b); System.out.println (b.toString()); </code></pre> <p>So, my question is: what is the implicit action taken when we have </p> <pre><code>System.out.println ((A)b); </code></pre> <p>? </p> <p>I suppose that the type of the reference variable b is automatically changed from B to A. The variable should still be pointing to the same object - the one created with </p> <pre><code>B b = new B(); </code></pre> <p>but just the type of b would be now changed. Is this correct? Another question: even though I have changed the type of b to the type of the superclass, are the overriden methods in the subclass going to be called, and not those of the superclass? </p> <p>Thanks a lot.</p> <p>Regards</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload