网站首页 语言 会计 电脑 医学 资格证 职场 文艺体育 范文
当前位置:书香门第 > 计算机 > java语言

Java中对象类型如何进行转换

栏目: java语言 / 发布于: / 人气:3.33W

导语: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类的成员.

}

}

Tags:JAVA 转换