多态

解决代码冗余问题,

比如说,定义一个类dog,dog类会汪汪叫,里面就有一个叫的方法叫shout(),但是如果有另外一个类cat类,cat类会喵喵叫,这样的话需要又定义一个shout()方法,存在代码冗余,于是,可以定义一个父类宠物pet类,在里面定义一个shout方法,让子类来继承,子类只需要继承就行

public class Pet {
    private String name;

    public Pet() {
        super();
    }

    public Pet(String name) {
        this.name = name;
    }

    public void shout(Pet pet){
        System.out.println(pet.name+"在叫唤");
    }

    public static void main(String[] args) {
        Pet pet=new Pet();
        pet.shout(new Dog("小狗狗"));//汪汪 小狗狗在叫唤
        pet.shout(new Cat("小猫猫"));//喵喵 小猫猫在叫唤
    }
}

  

public class Dog extends Pet {

    public Dog(String name) {
        super(name);
        System.out.println("汪汪");
    }
}

public class Cat extends Pet {

    public Cat(String name) {
        super(name);
        System.out.println("喵喵");
    }
}

  在父类中shout()形参是父类引用,而在实际参数是子类对象,这里涉及了向上转化的知识

原文地址:https://www.cnblogs.com/guochengfirst/p/9425370.html