java-多态的向上向下转型

package com.多态;

public class Demo1 {

  /**
  * @param args
  * int i=10;
  * byte j=20;
  * i=j;//自动类型提升
  * j=(byte)i;//自动类型转换
  */
  public static void main(String[] args) {

    Animal2 a=new Cat();//父类引用指向子类对象。就是向上转型
    System.out.println(a.num);//10,a引用只能看到父类对象属性值
    a.eat();//编译看到父类方法,运行子类方法
    Cat c=(Cat)a;//向下转型,引用c就能看到子类对象
    c.fly();
  }

}
class Animal2{
  int num=10;
  public void eat(){
    System.out.println("动物吃");
  }
}
class Cat extends Animal2{
  int num=20;
  public void eat(){
    System.out.println("猫吃");
}
  public void fly(){
    System.out.println("猫飞");
  }
}

posted @ 2018-01-07 22:38  简简单单zjl  阅读(774)  评论(0编辑  收藏  举报