1. 程式人生 > >JAVA父類物件與子類物件-造型轉換[轉]

JAVA父類物件與子類物件-造型轉換[轉]

描述1:Java中子類物件可以直接賦給父類物件,這個時候父類物件引用的就是子類物件的記憶體空間。
例如:class A
        {
                           ……
                      }
                      class B extends A
                      {
                           ……
                       }
則可以:B b=new B();
               A a=b;//父類物件a引用了子類物件b指向的記憶體空間。正確。
或者可以直接:A a=new B();//正確
描述2
:Java中將父類物件賦給子類物件時,要進行造型轉換(即強制型別轉換)
例如:

class People
{
int id;
String name;
People()
{
}
People(int id,String name)
{
   this.id=id;
   this.name=name;
}
}
class Student extends People
{
float score;
Student()
{
}
Student(int id,String name,float score)
{
   this.id=id;
   this.name=name;
   this.score=score;
}
}
public class hello
{
public static void main(String[] args)
{
   Student stu=newStudent(1,"jj",88);
  
People p=newPeople(3,"cc");
  stu=(Student)p;//父類物件造型轉換後賦給子類
  System.out.println(stu.id);

}
}
上面的源程式可以同過編譯,但在解釋執行時會丟擲classcastException異常
這是因為:可以執行型別轉換“子=(子)父”,但需要執行時進行檢查。如果父類變數引用的是正確的子型別(這句話的意思即為描述1中的內容:即父類物件要想造型轉換後賦給子類物件,其本身引用的是子型別的記憶體空間),賦值將執行。如果父類變數引用的是不相關的子型別,將會生成classcastException異常。

描述3:將描述2的原始碼改為下面的形式,在執行時就不會丟擲classcastException

異常了。

class People
{
int id;
String name;
People()
{
}
People(int id,String name)
{
   this.id=id;
   this.name=name;
}
}
class Student extends People
{
float score;
Student()
{
}
Student(int id,String name,float score)
{
   this.id=id;
   this.name=name;
   this.score=score;
}
}
public class hello
{
public static void main(String[] args)
{
   Student stu=newStudent(1,"jj",88);
  
  Peoplep=new Student(3,"cc",99);
stu=(Student)p;
  System.out.println(stu.id);

}
}
總結:

對類進行造型轉換的應參考以下原則:
1.總是可以“父=子”賦值。此時不需要型別轉換。
2.可以執行型別轉換“子=(子)父”,但需要執行時進行檢查。如果父類變數引用的是正確的子型別,賦值將執行。如果父類變數引用的是不相關的子型別,將會生成classcastException異常。
即:如果父類的例項是在子類的例項上塑造的,“子=(子)父”時就不會丟擲異常。  
如:
A 是B的父類。
A a= new B(); //父類A的物件a是在子類B的物件上塑造的。
就可以:
B b= (B)a;
3.決不能在不相關的任何類之間執行類的賦值或者型別轉換。即類的造型轉換僅限於有繼承關係的倆個類的物件之間。