java21对象的转型

来源:互联网 发布:网约车用什么软件好 编辑:程序博客网 时间:2024/05/29 18:10

此章非常重要

  1. 对象的向上转型:将子类的对象赋值给父类的应用。
    Student s = new Student();
    Person p = s;或者Person p = new Student();
Created with Raphaël 2.1.0StudentStudentPersonPerson向上转型被继承

一个引用能够使用哪些成员(变量和函数),取决于这个引用的类,所以对象p只能使用Person类中定义的变量和函数。
一个引用调用哪个方法取决于这个引用所指向的对象,由于p由对象s赋值指向的对象是Student中的函数所以只能调用Student中调用的方法。
向上转型不会失败。
2. 向下转型
Student s1 = new Student();
Person p = s1;
Student s2 = (Student)p;
必须先向上转型再向下转型。

0 0