diff --git a/day10/src/com/inmind/duotai08/interface_duotai/Demo12.java b/day10/src/com/inmind/duotai08/interface_duotai/Demo12.java new file mode 100644 index 0000000..c96fd50 --- /dev/null +++ b/day10/src/com/inmind/duotai08/interface_duotai/Demo12.java @@ -0,0 +1,23 @@ +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(); + } + } +} diff --git a/day10/src/com/inmind/duotai08/interface_duotai/MyInterface.java b/day10/src/com/inmind/duotai08/interface_duotai/MyInterface.java new file mode 100644 index 0000000..95a8740 --- /dev/null +++ b/day10/src/com/inmind/duotai08/interface_duotai/MyInterface.java @@ -0,0 +1,5 @@ +package com.inmind.duotai08.interface_duotai; + +public interface MyInterface { + public abstract void show(); +} diff --git a/day10/src/com/inmind/duotai08/interface_duotai/MyInterfaceImpl.java b/day10/src/com/inmind/duotai08/interface_duotai/MyInterfaceImpl.java new file mode 100644 index 0000000..bdcd59a --- /dev/null +++ b/day10/src/com/inmind/duotai08/interface_duotai/MyInterfaceImpl.java @@ -0,0 +1,13 @@ +package com.inmind.duotai08.interface_duotai; + +public class MyInterfaceImpl implements MyInterface{ + @Override + public void show() { + System.out.println("实现类的show方法"); + } + + + public void show1() { + System.out.println("实现类的show1方法"); + } +}