13.对象的转型

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





posted @ 2016-08-28 17:17  ArronEve  阅读(116)  评论(0编辑  收藏  举报