day09-接口和实现类的多态

This commit is contained in:
2026-01-25 11:21:21 +08:00
parent df9c7fc6f9
commit 8da93fa501
3 changed files with 41 additions and 0 deletions

View 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();
}
}
}

View File

@@ -0,0 +1,5 @@
package com.inmind.duotai08.interface_duotai;
public interface MyInterface {
public abstract void show();
}

View File

@@ -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方法");
}
}