1、多态概念
父类引用指向子类对象,从而产生多种形态。
2、多态形成的条件
二者具有直接或者间接的继承关系时,父类引用可指向子类对象,即形成多态。
3、注意点
父类引用指向子类对象,只能使用父类的实例变量和实例方法。
如果子类重写父类方法,则优先使用子类重写的方法
// Animal类
public class Animal {
String name;
public void eat() {
System.out.println("chi");
}
}
// Dog 类
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("dog在吃");
}
}
// TestDog 类
public class TestDog {
public static void main(String[] args) {
Animal a = new Dog();
a.eat();// dog在吃
}
}
4、多态使用场景
(1)使用父类作为方法的形参实现多态,使方法参数的类型更为宽泛
// Animal类
public class Animal {
String name;
public void eat() {
System.out.println("chi");
}
}
// Dog 类
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("dog在吃");
}
}
// Bird 类
public class Bird extends Animal {
@Override
public void eat() {
System.out.println("bird在吃");
}
}
// Master 类
public class Master {
String name;
public void feed(Animal animal) {
System.out.println(name + "喂食");
animal.eat();
}
}
// TestMaster 类
public class TestMaster {
public static void main(String[] args) {
Master a = new Master();
a.name = "小红";
Dog dog = new Dog();
Bird bird = new Bird();
a.feed(dog);
a.feed(bird);
}
}
image.png
(2)使用父类作为方法返回值实现多态,使方法可以返回不同的子类对象
// Animal类
public class Animal {
String name;
public void eat() {
System.out.println("chi");
}
}
// Dog 类
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("dog在吃");
}
}
// Bird 类
public class Bird extends Animal {
@Override
public void eat() {
System.out.println("bird在吃");
}
}
// Master 类
public class Master {
String name;
public Animal buy(int type) {
Animal animal;
if (type == 1) {
animal = new Dog();
} else {
animal = new Bird();
}
return animal;
}
}
// TestMaster 类
public class TestMaster {
public static void main(String[] args) {
Master a = new Master();
a.bug(1);
a.buy(2);
}
}
5、向上类型转换(装箱)
父类引用中保存真实子类对象,称为向上转型(即多态核心概念);
6、向下转型(拆箱)
前提是需要有向上转型。
// Animal 类
public class Animal {
public void eat() {
System.out.println("chi");
}
}
// Dog 类
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("dog在吃");
}
}
// TestAnimal 类
public class TestAnimal {
public static void main(String[] args) {
Animal a = new Dog();
a.eat();
Dog dog = (Dog)a;
dog.eat();
}
}
image.png
7、instanceof 关键字
向下转型前,应该判断引用中的对象真实类型,保证类型转换的正确性。
语法:引用 instanceof 类型 (返回boolean)
// Animal 类
public class Animal {
public void eat() {
System.out.println("chi");
}
}
// Dog 类
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("dog在吃");
}
}
// TestAnimal 类
public class TestAnimal {
public static void main(String[] args) {
Animal a = new Dog();
a.eat();
if (a instanceof Dog) {
Dog dog = (Dog)a;
dog.eat();
}
}
}