1 package Day3.Demo2;
2
3 /**
4 * 体现多态的写法,是下面的run方法,run方法在面向的是一个抽象的Car
5 * 在run方法看来,它只看Car,这个抽象的东西,具体是宝马,还是奔驰,run不关心
6 */
7 public class App {
8 public static void main(String[] args) {
9 //多态:通俗理解,我要来个人(抽象)帮帮我
10 //多态:是对象多种表现形式的体现,同一个事件发生在不同的对象上会产生不同的结果
11 Car car1 = new Bmw();
12 Car car2 = new Benz();
13 //多态:就是同一个接口,使用不同的实例而执行不同操作
14 run(car1);
15 run(car2);
16
17 }
18 /**
19 * 马路在跑车
20 * @param car
21 */
22 private static void run(Car car){
23 System.out.println("马路在跑车"+car.getBrand()+"车");
24 }
25 }
1 package Day3.Demo2;
2
3 public class Benz extends Car{
4 public Benz(){
5 super("奔驰","456");
6 }
7 }
1 package Day3.Demo2;
2
3 public class Bmw extends Car{
4 String aaa="222";
5 public Benz b=new Benz();
6
7 public void setAaa(String aaa) {
8 this.aaa = aaa;
9 }
10
11 public Bmw(){
12 super("宝马","123");
13 }
14 }
1 package Day3.Demo2;
2
3 public class Car {
4 private String brand;
5 private String output;
6 private int speed;
7
8 public Car(){
9
10 }
11
12 public Car(String brand, String output) {
13 this.brand = brand;
14 this.output = output;
15 }
16
17 public String getBrand() {
18 return brand;
19 }
20
21 public String getOutput() {
22 return output;
23 }
24
25 public void setBrand(String brand) {
26 this.brand = brand;
27 }
28
29 public void setOutput(String output) {
30 this.output = output;
31 }
32
33 public int getSpeed(){
34 return speed;
35 }
36
37 public void setSpeed(int speed){
38 if(speed<0){
39 return;
40 }
41 this.speed=speed;
42 }
43 }
instanceof关键字
作用:用于判断对象是否是某个对象的实例
语法:obj instanceof Class
使用场景:多态实现时,用于前置判断,避免类转化异常
例子:
1 private static void run(Car car){
2 if(car instanceof George){
3 System.out.println("不行,不让跑");
4 return;
5 }
6 System.out.println("马路在跑车"+car.getBrand()+"车");
7 }
多态
面向抽象编程
多态是继承内的