java 多态
多态是同一个行为具有多个不同表现形式或形态的能力。
同样的一个东西在不同的情况下可能会发生不同的变化
比如一张照片由单反照出来或者由诺基亚照出来就是完全不同的两张照片
多态的优点
1 消除类型之间的耦合关系
2. 可替换性
3. 可扩充性
4. 接口性
5. 灵活性
6. 简化性
多态存在的三个必要条件
1.继承
2.重写
3.父类引用指向子类对象:Parent p = new Child();
class Shape {
void draw() {}
}
class Circle extends Shape {
void draw() {
System.out.println("Circle.draw()");
}
}
class Square extends Shape {
void draw() {
System.out.println("Square.draw()");
}
}
class Triangle extends Shape {
void draw() {
System.out.println("Triangle.draw()");
}
}
当使用多态方式调用方法时,首先检查父类中是否有该方法,如果没有,则编译错误;如果有,再去调用子类的同名方法。
多态的好处:可以使程序有良好的扩展,并可以对所有类的对象进行通用处理。
public class Test {
public static void main(String[] args) {
show(new Bird());
show(new Dog());
Animal a = new Cat();
a.eat();
Bird c = (Bird)a;
c.work();
}
public static void show(Animal a) {
a.eat();
if (a instanceof Bird) {
Bird c = (Bird)a;
c.work();
} else if (a instanceof Dog) {
Dog c = (Dog)a;
c.work();
}
}
}
abstract class Animal {
abstract void eat();
}
class Bird 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("看家");
}
}
多态的实现方式
方式一:重写:
方式二:接口
方式三:抽象类和抽象方法