0%

java | 多态

多态在项目中的应用。

简单的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.redisc;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

class Animal{
public String name = "anmail";

public void run(){
System.out.println(name + " run");
}
}

class Cat extends Animal{
public String name = "cat";

@Override
public void run() {
System.out.println(name + " cat run");
}
}

class Doge extends Animal{
public String name = "doge";

@Override
public void run() {
System.out.println(name + " doge run");
}
}

public class Test {
public static void main(String[] args) {
Animal animal = new Doge();
animal.run();
System.out.println(animal.name);
}
}

输出

1
2
doge doge run
anmail

其中

1
Animal animal = new Doge();

就是多态的应用。

有一些细节

  • 方法:编译看左边,运行看右边
  • 变量:编译看左边,运行看左边

上面的输出已经说明了情况。

强制转换

因为,使用父类的话,不能使用自己特定行为,所以,要进行强制类型转换。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.redisc;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

class Animal {
public String name = "anmail";

public void run() {
System.out.println(name + " run");
}
}

class Cat extends Animal {
public String name = "cat";

@Override
public void run() {
System.out.println(name + " cat run");
}
}

class Doge extends Animal {
public String name = "doge";

@Override
public void run() {
System.out.println(name + " doge run");
}

public void dogeSkill() {
System.out.println("看家");
}
}

public class Test {
public static void main(String[] args) {
Animal animal = new Doge();
if (animal instanceof Doge) {
Doge doge = (Doge) animal;
doge.dogeSkill();
}
}
}
请我喝杯咖啡吧~