多态:意味着允许不同类的对象对同一消息做出不同的响应。
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();
}
}
输出:
动物都有吃东西的能力
猫吃鱼~
狗吃肉~