您的位置:首页 > 编程语言 > Java开发

java基础---对象的转型

2013-10-01 20:23 363 查看
向上转型--将子类的对象赋值给父类的引用

Student s = new Student();

Person p = s;

父类:

class Person{
String name;
int age;

void introduce(){
System.out.println("我的名字" + name + "我的年龄" + age);
}
}


子类:

class Sutdent extends Person{
String address;

void introduce(){
super.introduce();
System.out.println("我的家在" + address);
}
}

主函数:

class Test{
public static void main(String args []){
Student s = new Student();
Person p = s;
}
}


需要记住的语法要点:

       1、一个引用能够调用哪些成员(变量和函数),取决于这个引用的类型

              Eg:p.address 是错误的,因为person没有这个成员变量,所以无法调用。

        2、一个引用调用的是哪一个方法,取决于这个引用所指向的对象

              Eg:p.introduce()调用的其实是student中的introduce

向下转型---将父类的对象赋值给子类的引用

Student s1 = new Student();

Person p = s1;       //向上转型

Student s2 = (Student)p; //这就是向下转型

错误的向下转型的例子:

Person p = new Person();

Student s = (Student)p; //无法将一个父类生成的引用直接向下转成子类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: