多态对的前提:继承和方法重写
多态:父类引用指向子类对象,调用相同的方法,运行结果不同
多态的三个必要条件
- 继承
- 方法重写
- 父类引用 new 子类对象
多态的好处
- 减少重载方法的数量
- 符合开闭原则,即使增加子类,不需要提供额外的方法
多态的使用场合
- 使用父类做方法的形参,实参可以是任意的子类类型(最主要的场合)
- 使用父类做方法的返回值类型,实际返回的可以是任意子类的对象
父类
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();
}
}