當前位置:才華齋>計算機>java語言>

Java中物件型別如何進行轉換

java語言 閱讀(3.26W)

導語:Java中物件型別如何進行轉換呢?下面是小編給大家提供的Java中物件型別的強制轉換程式碼實現,大家可以參考閱讀,更多詳情請關注應屆畢業生考試網。

Java中物件型別如何進行轉換

class person

{

void f1()

{

tln("person f1 is calling !");

}

void f2()

{

f1();

}

}

class student extends person

{

void f1()

{

tln("student f1 is calling! ");

}

void f3()

{

tln("student f3 is calling!");

}

void f4()

{}

}

class Rt20

{

public static void main(String[]args)

{

student s=new student();

call(s);

}

public static void call(person p)//子類的物件可以自動轉換為父類的物件.

{

if(p instanceof student)//這句意思:p確實是student的物件嗎.

{

student s=(student)p;//把person型別強制轉換為student型別.

s.f1();

s.f2();

s.f3();

}

else

{

p.f1();

p.f2();

}

//p.f4();//p只能呼叫person類的`內容,雖然說p來源於student .但是它帶上person類的

//帽子,所以只能呼叫person類的成員.

}

}