
Java入门教程-面向对象三大特征之多态
1、多态的概念
多态是同一个行为具有多个不同表现形式或形态的能力。
多态就是同一个接口,使用不同的实例而执行不同操作,如图所示:
多态性是对象多种表现形式的体现。
同一个事件发生在不同的对象上会产生不同的结果。
2、多态的优点
消除类型之间的耦合关系
可替换性
可扩充性
接口性
灵活性
简化性
3、多态存在的三个必要条件
继承
重写
重写:子类对父类的允许访问的方法的实现过程进行重新编写,返回值和形参都不能改变。即外壳不变,核心重写。
重写的好处:在于子类可以根据需要,定义特定于自己的行为。也就是说子类能够根据需要实现父类的方法。
class Animal {
public void eat() {
System.out.println("正在吃...");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("狗正在吃狗粮...");
}
}
class Bird extends Animal {
public void eat() {
System.out.println("鸟正在吃鸟粮...");
}
}
public class Test1 {
public static void fun(Animal animal) {
animal.eat();
}
public static void main(String[] args) {
Dog dog = new Dog();
fun(dog);
Bird bird = new Bird();
fun(bird);
}
}
// 运行结果
狗正在吃狗粮...
鸟正在吃鸟粮...
重写(覆盖)的规则:
方法名相同
参数列表相同【顺序、个数、类型】
返回值相同
父类引用指向子类对象
比如:Animal dog = new Dog();
当使用多态方式调用方法时,首先检查父类中是否有该方法,如果没有,则编译错误;如果有,再去调用子类的同名方法。
多态的好处:可以使程序有良好的扩展,并可以对所有类的对象进行通用处理。
以下是多态的例子:
abstract class Animal {
abstract void eat();
}
class Cat extends Animal {
public void eat() {
System.out.println("吃鱼");
}
public void work() {
System.out.println("抓老鼠");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("吃骨头");
}
public void work() {
System.out.println("看家");
}
}
// 测试类
public class Test {
public static void show(Animal a) {
a.eat();
// 类型判断
if (a instanceof Cat) { // 猫做的事情
Cat c = (Cat)a;
c.work();
} else if (a instanceof Dog) { // 狗做的事情
Dog c = (Dog)a;
c.work();
}
}
public static void main(String[] args) {
show(new Cat()); // 以 Cat 对象调用 show 方法
show(new Dog()); // 以 Dog 对象调用 show 方法
Animal a = new Cat(); // 向上转型: 子类对象 -> 父类对象
a.eat(); // 调用的是 Cat 的 eat
Cat c = (Cat)a; // 向下转型: 父类对象 -> 子类对象
c.work(); // 调用的是 Cat 的 work
}
}
// 运行结果
吃鱼
抓老鼠
吃骨头
看家
吃鱼
抓老鼠
4、instanceof 关键字
Java中可以使用instanceof 关键字判断对象是否是某个类的实例,语法格式如下:
1)对象 instanceof 类
在上述格式中,如果对象是指定类的实例对象,则返回true,否则返回false。
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(this.name + "正在吃...");
}
}
class Dog extends Animal {
public String color;
public Dog(String name, int age,String color) {
super(name,age);
this.color = color;
}
public void eat() {
System.out.println(this.name + "正在吃狗粮...");
}
public void barks() {
System.out.println(this.name + "正在旺旺叫...");
}
}
class Bird extends Animal {
public Bird(String name, int age) {
super(name, age);
}
public void eat() {
System.out.println(this.name + "正在吃鸟粮...");
}
public void fly() {
System.out.println(this.name + "正在飞...");
}
}
public class Test1 {
public static void main(String[] args) {
Animal animal1 = new Dog("旺财",10,"黄色");
if (animal1 instanceof Bird){ // 判断 dog对象是否是Bird类的实例 如果是则实例化对象,否则打印hell
Bird bird2 = (Bird)animal1;
bird2.fly();
}else {
System.out.println("hell");
}
}
}