多态
多态是 同一个行为 具有 多个不同表现形式
实现方式:
1、继承父类,重写实现方法
2、实现接口,重写实现方法
3、抽象类
继承方式:
public class Printer { public void print() { System.out.println("I am Father Printer"); } } public class BlackPrinter extends Printer{ @Override public void print() { System.out.println("I am Black Printer!!!"); } } public class ColorfulPrinter extends Printer { @Override public void print() { System.out.println("I am Colorful Printer!!!"); } } public class Consumer { public static void main(String[] args) { Printer p1 = new Printer(); Printer p2 = new ColorfulPrinter(); Printer p3 = new BlackPrinter(); p1.print(); p2.print(); p3.print(); } } /*-------------输出如下---------------*/ I am Father Printer I am Colorful Printer!!! I am Black Printer!!!
接口方式
public interface Vehicle { void run(); } public class Bike implements Vehicle { @Override public void run() { System.out.println("Bike is Running ..."); } } public class Car implements Vehicle { @Override public void run() { System.out.println("Car Running..."); } } public class Consumer { public static void main(String[] args) { Vehicle v1 = new Car(); Vehicle v2 = new Bike(); v1.run(); v2.run(); } } /*---------------输出如下---------------*/ Car Running... Bike is Running ...