如何理解Java中的多态
什么是多态(Polymorphism)?
Java中的多态指:同一操作作用于不同的对象,可以有不同的解释,产生不同的执行结果。
实现
运行时多态的实现分 类继承 和 接口实现 两种
类继承实现运行时多态的三个必要条件:
- 类继承
- 子类重写父类的方法
- 父类的引用指向子类的对象
class Father{ public void hello(){ System.out.println("hello from father"); } } class Child extends Father{ // 1.类继承 @Override public void hello(){ // 2.子类重写父类方法 System.out.println("hello from child"); } } public class PolymorphismTest { @Test public void test() { Father father1 = new Father(); father1.hello(); //输出 hello from father Father father2 = new Child(); // 3.父类的引用指向子类的对象 father2.hello(); //输出 hello from child //Father类的 hello 方法有不同的解释,同时产生不同的执行结果 } }
接口实现 实现运行时多态的三个必要条件:
- 接口实现
- 实现类 实现 接口方法
- 接口的引用指向实现类对象
public interface Greetor { void hello(); } public class GreetorA implements Greetor { // 1.接口实现 @Override public void hello() { // 2.实现类 实现 接口方法 System.out.println("hello from greetor A"); } } public class GreetorB implements Greetor { // 1.接口实现 @Override public void hello() { // 2.实现类 实现 接口方法 System.out.println("hello from greetor B"); } } public class PolymorphismTest { @Test public void test() { Greetor greetor1 = new GreetorA(); // 3.接口引用指向实现类对象 greetor1.hello(); //输出 hello from greetor A Greetor greetor2 = new GreetorB(); // 3.接口引用指向实现类对象 greetor2.hello(); //输出 hello from greetor B //Greetor接口的 hello 方法有不同的解释,同时产生不同的执行结果 } }
上述的多态均指的是运行时多态(动态多态),即方法的重写(overriding)可以实现运行时多态
而方法的重载(overloading)有时也被称为静态多态
如果没有特殊说明,多态一般指的是运行时多态(动态多态)
上一篇:
IDEA上Java项目控制台中文乱码