Files
javaSE-0419/day10/src/com/inmind/duotai08/interface_duotai/Demo12.java

24 lines
947 B
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.inmind.duotai08.interface_duotai;
/*
接口和实现类的多态
多态的前提:
1.继承或实现
2.重写
3.父类引用指向子类对象
*/
public class Demo12 {
public static void main(String[] args) {
MyInterfaceImpl myInterface = new MyInterfaceImpl();//是不是多态???不是
//多态的格式:父类引用指向子类对象
//接口中的多态格式:接口类型 对象名 = new 实现类类型();
MyInterface myInterface1 = new MyInterfaceImpl();//多态的写法,向上转型
myInterface1.show();//编译看左边,运行看右边
//但是我就想要调用实现类的show1方法那怎么办
if (myInterface1 instanceof MyInterfaceImpl) {//为了类型转换时,避免出现类型转换异常,先判断类型
MyInterfaceImpl m = (MyInterfaceImpl)myInterface1; //向下转型
m.show1();
}
}
}