day09-接口和实现类的多态
This commit is contained in:
23
day10/src/com/inmind/duotai08/interface_duotai/Demo12.java
Normal file
23
day10/src/com/inmind/duotai08/interface_duotai/Demo12.java
Normal file
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.inmind.duotai08.interface_duotai;
|
||||||
|
|
||||||
|
public interface MyInterface {
|
||||||
|
public abstract void show();
|
||||||
|
}
|
||||||
@@ -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方法");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user