-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path42_Polymorphism
More file actions
64 lines (50 loc) · 1.2 KB
/
42_Polymorphism
File metadata and controls
64 lines (50 loc) · 1.2 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Polymorphism = greek word for poly-"many", morph-"form"
// The ability of an object to identify as more than one type
<Main.java>
public class Main{
public static void main(String[] args) {
Car car = new Car();
Bicycle bicycle = new Bicycle();
Boat boat = new Boat();
Vehicle[] racers ={car, bicycle, boat}; //All class extends to vehicle
//Method 1
/*car.go();
bicycle.go();
boat.go();*/
//Method 2
for (Vehicle x : racers){
x.go();
}
}
}
<Vehicle.java>
public class Vehicle {
public void go(){
System.out.println("*The bicycle begins moving*");
}
}
<Car.java>
public class Car extends Vehicle{
@Override
public void go(){
System.out.println("*The car begins moving*");
}
}
<Bicycle.java>
public class Bicycle extends Vehicle{
@Override
public void go() {
System.out.println("*The bicycle begins moving*");
}
}
<Boat.java>
public class Boat extends Vehicle {
@Override
public void go() {
System.out.println("*The boat begins moving*");
}
}
>>
*The car begins moving*
*The bicycle begins moving*
*The boat begins moving*