1. 多态的解释
在面向对象语言中,接口的多种不同的实现方式即为多态。
2. 示例
package com.lxh.polymorphism;
public interface GirlFriend {
// saylove
public void sayLove();
}
package com.lxh.polymorphism;
public class ChineseGirlFriend implements GirlFriend {
// 重写:子类的方法覆盖父类的方法,要求方法名和参数都相同
public void sayLove() {
System.out.println("亲爱的,我可喜欢你了。。。");
}
// 重载:同一个类中的两个或两个以上的方法,拥有相同的方法名,但是参数却不相同,方法体也不相同,最常见的重载的例子就是类的构造函数
public void sayLove(String girlName,String content){
System.out.println(girlName + " said, "+content);
}
}
package com.lxh.polymorphism;
public class ForeignGirlFriend implements GirlFriend {
@Override
public void sayLove() {
System.out.println("dear,I love you so much...");
}
}
package com.lxh.polymorphism;
/**
* 在面向对象语言中,接口的多种不同的实现方式即为多态。
*/
public class PolymorphismTest {
public static void main(String[] args) {
GirlFriend gf1 = new ChineseGirlFriend();
GirlFriend gf2 = new ForeignGirlFriend();
gf1.sayLove();
gf2.sayLove();
System.out.println("===========================================");
ChineseGirlFriend gf3 = new ChineseGirlFriend();
gf3.sayLove("小芳", "艾玛,俺可喜欢你咯。。。");
}
}
3. 小结:
<1> 多态的体现
父类的引用指向了自己的子类对象
父类的引用也可以接收自己的对象
<2> 多态的前提
必须是类与类之间只有关系,要么继承或实现
通常还有一个前提,存在覆盖
<3> 多态的好处
多态的出现大大的提高了程序的扩展性
<4> 多态的弊端
只能使用父类的引用访问父类的成员