向上转型--将子类的对象赋值给父类的引用
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; //无法将一个父类生成的引用直接向下转成子类