面向对象三大特征——多态

多态对的前提:继承和方法重写

多态:父类引用指向子类对象,调用相同的方法,运行结果不同
多态的三个必要条件
  1. 继承
  2. 方法重写
  3. 父类引用 new 子类对象
多态的好处
  1. 减少重载方法的数量
  2. 符合开闭原则,即使增加子类,不需要提供额外的方法
多态的使用场合
  1. 使用父类做方法的形参,实参可以是任意的子类类型(最主要的场合)
  2. 使用父类做方法的返回值类型,实际返回的可以是任意子类的对象
    父类
public class Animal {
    private int age;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Animal(int age) {
        this.age = age;
    }
    public Animal() {
    }
    public void introduce(){
        System.out.println("今年"+this.getAge()+"岁!");
    }
}

子类

public class Bird extends  Animal {
    private String color;
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public Bird(int age, String color) {
        super(age);
        this.color = color;
    }
    public Bird() {
    }
    @Override
    public void introduce() {
        System.out.println("我是一只"+color+"的鸟");
        super.introduce();
    }
    public void fly(){
        System.out.println("我可以展翅飞翔.....");
    }
}
public class Fish extends  Animal {
    private int weight;
    public int getWeight() {
        return weight;
    }
    public void setWeight(int weight) {
        this.weight = weight;
    }
    public Fish(int age, int weight) {
        super(age); //调用父类的带一个参数的构造方法
        this.weight = weight;
    }
    public Fish() {
         //省略了一句super(),调用父类的无参构造方法
    }
    @Override
    public void introduce() {
        System.out.println("我是一只"+weight+"斤重的鱼");
        super.introduce();//调用父类的成员方法
    }
    public void swimming(){
        System.out.println("我在水里自由的游泳");
    }
}

测试

public class Test {
    public static void main(String[] args) {
        //多态就一个重点步骤  :父类引用 new子类对象
        Animal bird=new Bird(2,"红色"); //等号的左侧称为编译时类型
        Animal fish=new Fish(4,10); //等号的右侧是运行时类型,因为new在运行时在堆里开的空间
        bird.introduce();
       // bird.fly();
        System.out.println("-----------------------------");
        fish.introduce();
       // fish.swimming();
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值