day10--接口和实现类的多态
This commit is contained in:
@@ -0,0 +1,23 @@
|
|||||||
|
package com.inmind.interface_poly10;
|
||||||
|
/*
|
||||||
|
多态的前提:
|
||||||
|
1.继承或实现,二选一
|
||||||
|
2.要有重写
|
||||||
|
3.父类(接口)引用指向子类(实现类)对象
|
||||||
|
|
||||||
|
接口的多态:
|
||||||
|
父类类型 对象名 = new 子类类型();
|
||||||
|
接口类型 对象名 = new 该接口的实现类对象();
|
||||||
|
*/
|
||||||
|
public class Demo11 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
//普通的实现类对象
|
||||||
|
MyInterfaceImpl impl1 = new MyInterfaceImpl();
|
||||||
|
//接口的多态
|
||||||
|
MyInterface impl2 = new MyInterfaceImpl();
|
||||||
|
//多态的口诀:1.父类引用指向子类对象 2.编译看左边,运行看右边
|
||||||
|
impl2.method();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package com.inmind.interface_poly10;
|
||||||
|
|
||||||
|
public interface MyInterface {
|
||||||
|
void method();
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.inmind.interface_poly10;
|
||||||
|
|
||||||
|
public class MyInterfaceImpl implements MyInterface{
|
||||||
|
@Override//标记当前是重写的方法
|
||||||
|
public void method() {
|
||||||
|
System.out.println("实现类重写了抽象方法");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void show(){
|
||||||
|
System.out.println("实现类独有的方法");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user