向上转型案例

多态:意味着允许不同类的对象对同一消息做出不同的响应。
Java中的多态:程序运行时动态决定调用哪个方法。
必要条件:(1)满足继承关系
(2)父类引用指向子类对象
编写父类Animal和子类Cat,Dog:

package java_ploy;

public class Animal {
    //属性:昵称、年龄
    private String name;
    private int month;

    public Animal(){

    }

    public Animal(String name, int month){

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    //方法:吃东西
    public void eat(){
        System.out.println("动物都有吃东西的能力");
    }
}
package java_ploy;

public class Cat extends Animal {
    //属性:体重
    private double weight;

    public Cat(){

    }

    public Cat(String name, int month, double weight){
        super(name, month);  //this.setName(name);
        this.weight = weight;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }
    
    //方法:跑动
    public void run(){
        System.out.println("小猫模特步~");
    }

    //方法:吃东西(重写父类方法)
    @Override  //该符号表示下方代码是对父类方法的重写
    public void eat() {
        System.out.println("猫吃鱼~");
    }
}
package java_ploy;

public class Dog extends Animal {
    //属性:性别
    private String sex;

    public Dog(){

    }

    public Dog(String name, int month, String sex){
        super(name, month);
        this.sex = sex;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    //方法:睡觉
    public void sleep(){
        System.out.println("狗有午睡的习惯~");
    }

    //方法:吃东西(重写父类方法)
    @Override
    public void eat() {
        System.out.println("狗吃肉~");
    }
}

测试:
* 父类引用指向子类实例
* 称为向上转型、隐式转型、自动转型
* 可以调用子类重写父类的方法以及父类派生的方法,无法调用子类独有方法
* 小类转型为大类

package java_ploy;

public class Test {
    public static void main(String[] args) {
        Animal one = new Animal();
        /**
         * 父类引用指向子类实例
         * 称为向上转型、隐式转型、自动转型
         * 可以调用子类重写父类的方法以及父类派生的方法,无法调用子类独有方法
         * 小类转型为大类
         */
        Animal two = new Cat();
        Animal three = new Dog();

        one.eat();
        two.eat();
        two.setMonth(2); //可以调用子类重写父类的方法以及父类派生的方法
        //two.weight;  //无法调用子类独有方法
        three.eat();
    }
}

输出:

动物都有吃东西的能力
猫吃鱼~
狗吃肉~
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值