面向对象的三大特性:继承封装,多态
从一定角度来看,封装和继承几乎都是为多态准备的
定义
指的是不同对象对同一消息做出响应。即同一消息可以根据发送对象的不同而采用多种不同的行为方式。
多态要有动态绑定,否则就不是多态,方法重载也不是多态(因为方法重载是编译期决定好的,没有后期也就是运行期的动态绑定)
当满足这三个条件 1.有继承 2. 有重写 3. 要有父类引用指向子类对象
作用
消除类型之间的耦合关系
多态的好处
1)可替换性
2)可扩充性
3)接口性
4)灵活性
Java中多态的分类
分为方法的多态和类的多态
1)person为父类,student为子类,那么pesron p = new student();
2)fliable为接口,bird为实现接口的类,那么:fliable f=new bird();
3)fliable为抽象类,bird为继承fliable的类,那么:fliablef=new bird();
声明了person p=new student();我想将p转为student的可不可以?当然可以,但是就得强制转换了(儿子想成为父亲直接来,父亲想成为儿子你就强来)
class A
{
public String show(D obj)...{
return ("A and D");
}
public String show(A obj)...{
return ("A and A");
}
}
class B extends A
{
public String show(B obj)...{
return ("B and B");
}
public String show(A obj)...{
return ("B and A");
}
}
class C extends B{}
class D extends B{}
class E
{
public static void main(String [] args)
{
A a1 = new A();
A a2 = new B();
B b = new B();
C c = new C();
D d = new D();
System.out.println(a1.show(b)); //①
System.out.println(a1.show(c)); //②
System.out.println(a1.show(d)); //③
System.out.println(a2.show(b)); //④
System.out.println(a2.show(c)); //⑤
System.out.println(a2.show(d)); // ⑥
System.out.println(b.show(b)); //⑦
System.out.println(b.show(c)); //⑧
System.out.println(b.show(d)); //⑨
}
}
(三)答案
① A and A
② A and A
③ A and D
④ B and A
⑤ B and A
⑥ A and D
⑦ B and B
⑧ B and B
⑨ A and D