day10-接口和实现类的多态

This commit is contained in:
2026-07-27 16:27:16 +08:00
parent 61d11ecc4d
commit 2e3054287a
3 changed files with 40 additions and 0 deletions
@@ -0,0 +1,23 @@
package com.inmind.duotai_interface11;
import com.inmind.object_cast10.Animal;
import com.inmind.object_cast10.Cat;
/*
类的多态 :父类引用指向子类对象
接口的多态:接口引用指向实现类对象
*/
public class Demo11 {
public static void main(String[] args) {
MyInterfaceImpl myInterfaceImpl = new MyInterfaceImpl();//普通写法
Animal animal = new Cat();//向上转型
//接口引用指向实现类对象
MyInterface myInterface = new MyInterfaceImpl();//接口的多态(接口的向上转型)
myInterface.method();//编译看左边,运行看右边
if (myInterface instanceof MyInterfaceImpl){//接口的类型判断
MyInterfaceImpl impl = (MyInterfaceImpl) myInterface;//接口的向下转型
impl.method1();
}
}
}
@@ -0,0 +1,5 @@
package com.inmind.duotai_interface11;
public interface MyInterface {
void method();
}
@@ -0,0 +1,12 @@
package com.inmind.duotai_interface11;
public class MyInterfaceImpl implements MyInterface{
@Override
public void method() {
System.out.println("实现类实现了method方法");
}
public void method1(){
System.out.println("实现类1中method1方法");
}
}