多态
多态的目的:基类的引用指向子类的对象(引用相同,但是实际指向的对象不同,就可以实现不同的行为)
public static final int FIRST_CONDITION = 1;
public static final int TWO_CONDITION = 2;
public static final int THREE_CONDITION = 3;
public static final int GO_BEHAVIOR = 1;
public static final int BACK_BEHAVIOR = 2;
public static void main(String[] args) {
Random random = new Random();
int condition = random.nextInt(4);
Random randomConditon = new Random();
int behavior = randomConditon.nextInt(3);
if (condition == FIRST_CONDITION) {
if (behavior == GO_BEHAVIOR) {
System.out.println("First_Condition__GO_BEHAVIOR");
} else if (behavior == BACK_BEHAVIOR) {
System.out.println("First_Condition__BACK_BEHAVIOR");
}
} else if (condition == TWO_CONDITION) {
if (behavior == GO_BEHAVIOR) {
System.out.println("TWO_Condition__GO_BEHAVIOR");
} else if (behavior == BACK_BEHAVIOR) {
System.out.println("TWO_Condition__BACK_BEHAVIOR");
}
} else if (condition == THREE_CONDITION) {
if (behavior == GO_BEHAVIOR) {
System.out.println("Three_Condition__GO_BEHAVIOR");
} else if (behavior == BACK_BEHAVIOR) {
System.out.println("Three_Condition__BACK_BEHAVIOR");
}
}
}
多态写法:
public interface Behavior {
void go();
void back();
}
public class BaseCondition implements Behavior {
public void go() {
System.out.println("BaseCoditon_BEHAVIRO_GO");
}
public void back() {
System.out.println("BaseCoditon_BEHAVIRO_BACK");
}
}
public class FirstCondition extends BaseCondition {
public void go() {
System.out.println("First_Condition__GO_BEHAVIOR");
}
public void back() {
System.out.println("First_Condition__BACK_BEHAVIOR");
}
}
public class TwoCondition extends BaseCondition{
public void go() {
System.out.println("TWO_Condition__GO_BEHAVIOR");
}
public void back() {
System.out.println("TWO_Condition__BACK_BEHAVIOR");
}
}
public class ThreedCondition extends BaseCondition {
public void go() {
System.out.println("Three_Condition__GO_BEHAVIOR");
}
public void back() {
System.out.println("Three_Condition__BACK_BEHAVIOR");
}
}
public static void main(String[] args) {
BaseCondition baseCondition = new FirstCondition();
baseCondition.go();
}
对比:
1、非多态写法有如此之多的if与else,使问题与系统如此之复杂
2、多态写法只用根据基类引用指向的对象不同,从而不同类的不同实现,简单异常
3、面向对象中有六大法则,多态遵循了开闭原则,因为只用某个类的某个方法就可以改变本身的实现,对扩展开发,对修改关闭
补充小知识点:
1、编译器根据引用类型来判断有哪些方法可以使用,而不是该引用实际指向的对象
2、在程序运行时,会根据这个引用实际指向的类型,去调用不同的类型对这个方法的不同实现
3、在JAVA中是先有父后有子的世界,如果一个子类没有对该方法实现,才会去调用父类中对同一个方法的实现
public class Father implements eat{
public void eatFood() {
System.out.println("红烧肉");
}
}
public class ChildWangWu extends Father{
public void eatFood() {
System.out.println("肯德鸡");
}
public void sleep() {
System.out.println("睡觉");
}
}
public class ChildZhangSan extends Father {
public void eatFood() {
System.out.println("麦当劳");
}
}
public class Test {
public static void main(String[] args) {
Father father = new ChildWangWu();
father.eatFood();
}
}
输出:
肯德鸡
该输出证明了补充知识点的三个观点。