Why the parent class reference can point to a subclass reference to subclass object can not point to the parent class object generics

Suppose Fu parent class, subclass which Zi, from the perspective of the memory object, which is assumed Fu class account variables memory 2M, Zi class of memory for a variable 1M:

Fu f = new Fu (); // allocate system memory 2M

Zi z = new Zi (); // allocate system memory 3M (2 + 1)

Because the sub-class has a hidden reference to super will point to the parent class instance, so before instantiable subclass will first instantiate a parent class, that will be the first implementation of the parent class constructor. So z can call the parent class method.

Zi z1 = z; // z1 3M memory that point.

Fu f1 = (Fu) z; // At this point it will be f1 3M 2M RAM memory, that is, f1 simply point to an object instance of the parent class in Example z, you can call the parent class f1 methods ( 2M stored in memory), the method (1M stored in the memory) can not call subclass.

Zi z2 = (Zi) f; // This code will be reported runtime ClassCastException because f only 2M memory, and subclass references must be 3M's memory, it can not be converted.

Zi f1 z3 = (Zi); // phrase by running, then that point z3 3M memory f1 is converted by z since over, so it is 3M's memory, but it points in 2M 3M. memory, type conversion, you can get all 3M.

 

In the absence of a generic type of class Class, not all new. Type can only be used strong turn

Here is a case of type conversion

Object[] ins= {  
                new Integer(0),  
                new Integer(1),  
                new Integer(2),  
                new Integer(3),  
         };  
        Integer[] i = (Integer[]) ins;  

When executed, the system reported 
Exception in thread "main" java.lang.ClassCastException:  [Ljava.lang.Object; can not be cast to [Ljava.lang.Integer;

If you changed the way it below:

  Object[] ins= {     
        new Integer(0),     
         new Integer(1),     
         new Integer(2),     
          new Integer(3),     
  };     
 Integer[] i = new Integer[ins.length];  
 for(int k = 0; k < ins.length; k++){  
    i[k] = Integer.parseInt(ins[k].toString());  
     System.out.println(i[k]);  
 }

Why Object [] array can not turn into a strong Integer [] array it?

In fact, Object [] array and Integer [] array and no prior relationship between the inheritance relationship, Integer [] is a subclass of Object, not Object [] array and the like.

Object [] array is the class of Object .....

Strong turn, then still have to be one of the strong turn of the individual elements.

 

----------------
Original link: https://blog.csdn.net/lifewinnerforever/article/details/72801247

Guess you like

Origin www.cnblogs.com/skyblue123/p/12610641.html