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

- 一个引用能够调用那些成员(变量和函数),取决于这个引用的类型
- 一个引用调用的是哪一个方法,取决于这个引用所指向的对象
classPerson{String name;int age;void introduce(){System.out.println("我的名字是:"+ name +",我的年龄是:"+ age);}}
classStudent extends Person{String address;void study(){System.out.println("我正在学习");}void introduce(){super.introduce();System.out.println("我的家在"+ address);}}
classTest{publicstaticvoid main(String args []){Student s =newStudent();Person p = s;p.name ="张三";p.age =20;s.address = "北京";p.introduce();//p.study();}}
结果:
D:\work\src>javac *.java
D:\work\src>java Test
我的名字是:张三,我的年龄是:20
我的家在北京
- 对象的向下转型
- 面向对象多态性的体现
- 将父类的对象赋值给子类的引用

- 先把一个对象向上转型,再向下转型
classTest{publicstaticvoid main(String args []){//Student s = new Student();//Person p = s;Person p =newStudent();Student s =(Student)p;//错误的向下转型//Person p = new Person();//Student s = (Student)p;}}

浙公网安备 33010602011771号