File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class Adapter {
2
+ public static void xiaoMing (BicycleInterface b ) {
3
+ b .ride ();
4
+ }
5
+
6
+ public static void main (String [] args ) {
7
+ Bicycle b = new Bicycle ();
8
+ Car c = new Car ();
9
+
10
+ xiaoMing (b );
11
+ // xiaoMing(c); //类型不匹配
12
+
13
+ CarAdapter ca = new CarAdapter (c ); // 将 Car 适配成 Bicycle
14
+ xiaoMing (ca ); // 小明可以用了
15
+ }
16
+ }
17
+
18
+ class CarAdapter implements BicycleInterface {
19
+ private Car car ;
20
+
21
+ public CarAdapter (Car car ) {
22
+ this .car = car ;
23
+ }
24
+
25
+ public void ride () {
26
+ car .drive ();
27
+ }
28
+ }
29
+
30
+ interface BicycleInterface {
31
+ void ride ();
32
+ }
33
+
34
+ class Bicycle implements BicycleInterface {
35
+ public void ride () {
36
+ System .out .println ("I am riding a bicycle." );
37
+ }
38
+ }
39
+
40
+ interface CarInterface {
41
+ void drive ();
42
+ }
43
+
44
+ class Car implements CarInterface {
45
+ public void drive () {
46
+ System .out .println ("I am driving a car." );
47
+ }
48
+ }
You can’t perform that action at this time.
0 commit comments