java多态方法成员变量分析

/**
 * 测试多态成员与方法用例
 * @author vcerhj
 * Animal父类,Bird为继承父类的子类.
 */
 class Animal {    //父类Animal
    protected int a=2;
    Animal(){            //父类构造方法
        System.out.println("Please write an animal");
    }
    public  void eat(){
        System.out.println("eat eat");
    }
    public  void run() {
        System.out.println("Run with your feet");
    }
    public void rest(){
        System.out.println("take a break");
    }
  }
class Bird extends Animal {    //继承父类Animal的子类Bird
    protected int a =3;
    Bird() {                  //子类构造方法
        super();
        System.out.println("请写出一个鸟类");
    }

    public void eat() {
        System.out.println("叽叽叽");
    }

    public  void run() {      //重写父类的run方法,实际为覆盖.
        System.out.println("fly");
    }
    public void fly (){
        System.out.println("fly fly ");
    }
}

public class text {
    public static void  main(String[] args){
        Animal one = new Animal();
        one.run();
        System.out.println(one.a);

        Bird two = new Bird();
        two.run();
        System.out.println(two.a);

        Animal t = new Bird();  //当一个父类的引用指向一个子类对象时。
        t.run();    //调用实则为子类的方法.
      /*t.fly();*/     //无法调用子类新增的方法.
        System.out.println(t.a);  //调用父类的成员变量
        Bird t1 =(Bird) t;
        System.out.println(t1.a); //调用子类的成员变量

    }
}

输出为:

Please write an animal       //创建父类对象调用父类构造器
Run with your feet              //输出父类语句
2                                        //输出父类的变量a
Please write an animal      //创建子类对象调用父类构造器
请写出一个鸟类                 //调用子类构造器
fly                                      //输出子类语句
3                                       //输出子类的变量a
Please write an animal    
请写出一个鸟类
fly                                   //调用子类的语句
2                                    //输出父类的变量a
3                                   //输出子类的变量a

调用成员变量时,将调用引用类型所对应的类中的成员变量,如果该类中没有定义该变量,而其父类中定义了同名的成员变量,那么将调用其父类中的同名变量。

调用成员方法时,将根据对象的运行时类型来确定调用哪个类中定义的成员方法。运行时类型是哪个类的类型,那么就调用哪个类中定义的成员方法。

转载于:https://www.cnblogs.com/algorithmvcerhj/p/8546060.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值