Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are two issues that are getting confused here, the type of a variable or expression, and the class of an object.</p> <p>Each object has a class that is established when it is created through "new" or clone(). That class is fixed for the lifetime of the object.</p> <p>An reference variable or expression is either null or a pointer to some object. The type of a reference variable is indicated by the name of a class or interface. It can only reference a object if the class of the object matches or extends, directly or indirectly, the class, or implements the interface. In effect, the type of the variable guarantees that the object has the corresponding members.</p> <pre><code>A a = new A(); //statement 1 </code></pre> <p>Declares a variable "a" with type A, meaning it can only be null or a pointer to an A, or an object whose class extends A. Initializes it as a pointer to a newly created object of class A.</p> <pre><code>A a1= new B(); //statement 2 </code></pre> <p>Declares a variable "a1" with type A, meaning it can only be null or a pointer to an A, or an object whose class extends A. Initializes it with a pointer to a newly created B. Since B extends A, the conversion of a type B expression to type A is permitted.</p> <pre><code>B b= (B) new A(); // statement 3 </code></pre> <p>The difference here is that A does not extend B. A type A reference can be cast to type B if, and only if, it is null or a pointer to an object of class B, or a class that extends B. Class A does not extend B. The compiler will accept this, because the cast claims that "new A()" is null or refers to a class B object, or an object of a class extending B. It will get a ClassCastException at run time, because that claim is false.</p> <p>The type of a reference variable or expression is determined at compile time. In the course of a program run, it may be null or refer to objects of several different classes, but only class that are appropriate for its declared type.</p>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      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