什么是多态
同一件事情上,发生在不同对象上,就会产生不同的行为
多态实现条件
在
java
中要实现多态,必须要满足如下几个条件,缺一不可:
1. 必须在继承体系下2. 子类必须要对父类中方法进行重写3. 通过父类的引用调用重写的方法
多态体现:在代码运行时,当传递不同类对象时,会调用对应类中的方法。
class Animal {
public String name;//名字
public int age; //年龄
public Animal(String name,int age) { //父类的构造方法
this.name = name;
this.age =age;
}
public void eat() {
System.out.println("正在吃...");
}
// public final void eat(){
// System.out.println("正在吃..."); //被final修饰的方法 ,不能被重写,称为密封方法
// }
// public static void eat(){
// System.out.println("正在吃...");//被static修饰的方法 ,不能被重写
// }
}
class Dog extends Animal {
public String color;//颜色
public Dog(String name, int age, String color) {
super(name,age);
this.color = color;
}
@Override
public void eat() {
System.out.println(this.name +"正在吃狗粮...");
}
}
class Cat extends Animal{
public Cat(String name ,int age) {
super(name,age);
}
@Override
public void eat() {
System.out.println(this.name +"正在吃猫粮...");
}
}
class Bird extends Animal{
public Bird(String name ,int age) {
super(name,age);
}
@Override
public void eat() {
System.out.println(this.name +"正在吃虫子...");
}
public void fly() {
System.out.println(this.name +"正在飞...");
}
}
public class Test1 {
public static void eatFood(Animal a) {
a.eat();//方法传参:形参为父类引用,可以接收任意子类对象
}
public static Animal fun(){
return new Bird("布谷",2);
}
public static void main(String[] args) {
Animal animal = new Dog("旺财",1,"黄色");
animal.eat();
Cat cat = new Cat("墩墩",1);
eatFood(cat);
Animal animal1 = fun();
animal1.eat();
//animal1.fly();//不能调用子类特有的方法
Bird bird = (Bird) animal1;
bird.fly();//animal1 本来是鸟 将其还原成鸟也是安全的
// Dog dog=new Dog("旺财",2,"黄色");
// dog = (Dog)animal1; 本来是鸟,还要强行还原成狗,无法正常还原,运行时抛出 ClassCastException
if(animal1 instanceof Bird) {
Bird bird2 = (Bird) animal1;
bird2.fly();
}else {
System.out.println("hello");
}
}
}
要想更好的认识多态
1、理解向上转型
向上转型:实际就是创建一个子类对象,将其当成父类对象来使用。语法格式:父类类型 对象名 = new 子类类型 ()
三种方式
a、直接赋值 (两种形式)
b、通过传参
c、通过返回值
理解多态
发生了动态绑定 :编译的时候 认为还确实是 调用父类的eat方法 运行当中 绑定到了子类当中
静态绑定:编译的时候,应经确定要调用哪个方法
向上转型:
优点:让代码更灵活
缺点:不能调用子类特有的方法
2、重写
即外壳不变,内核重写
1、方法名形同
2、参数列表相同(顺序 个数 类型)
3、返回值相同
注:重写的方法可以使用@Override 注解来显示指定
1、被final修饰的方法,不能被重写,被称之为密封方法
被static关键字或者private关键字修饰的方法 ,不能被重写
子类重写父类方法时,子类的方法访问修饰限定符>=父类