首页 > 学院 > 开发设计 > 正文

对象的转型

2019-11-14 21:40:41
字体:
来源:转载
供稿:网友
对象的转型

对象的转型分为向上转型和向下转型

向上转型:将子类的对象赋值给父类的引用,如

Student s = new Student();Person P = s ;

Student是Person的子类(继承)。首先声明了student的引用s,再同new关键字调用了构造函数生成student的对象,并把对象赋值给引用s,s指向对象。再把s赋值给Person类型的引用p

class Person{      String name;      void introduce(){           System.out.PRintln("我叫" + name);      }}
class Student extends Person{      int age;      void study(){           System.out.println("我正在学习");      }          void introduce(){           super.introduce();           System.out.println("我" + age);      }}
class Test{      public static void main(String args[]){           Student s = new Student();           Person p = s;           //等同于 Person p = new Student();           p.name = "lisi";           p.age = 20;           p.study();      }}

错误原因:根据上图所示,虽然s和p指向同一个对象,但一个引用能够调用的成员(变量和函数),取决于这个引用的类型,如p是Person的引用,p能调用的成员取决于Person中所定义的成员。

在父类中有个方法A,在子类中对方法A进行复写后(父类方法A被覆盖),一个引用所调用的方法,取决于这个引用所指向的对象。p指向Student对象,p调用introduce(),结果如下。

p.introduce();

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

Student s1 = new Student();Person P = s1 ;Student s2 = (Student)p;//强制类型转换

向下转型的前提首先进行向上转型。父类对象的引用无法直接转型为子类的类型


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表