-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolymorph.java
More file actions
106 lines (81 loc) · 1.98 KB
/
Polymorph.java
File metadata and controls
106 lines (81 loc) · 1.98 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import java.io.*;
public class Polymorph{
static abstract class Pen
{
String writeColour;
public abstract void returnWriteColour();
}
static class Ballpoint extends Pen
{
public Ballpoint( String e )
{
writeColour = e;
}
public void returnWriteColour()
{
System.out.println("The ballpoint's write colour is " + writeColour + ",\n");
}
}
static class Colourpencil extends Pen
{
public Colourpencil( String e )
{
writeColour = e;
}
public void returnWriteColour()
{
System.out.println("The colour pencil's write colour is " + writeColour + ".\n");
}
}
//////////////////////////////////////////////////////////////////
public static void main(String[] args) throws IOException
{
Pen somePen = new Ballpoint( "blue" );
somePen.returnWriteColour();
System.out.println(somePen.getClass());
somePen = new Colourpencil( "red" );
somePen.returnWriteColour();
System.out.println(somePen.getClass());
class Car {
public void drive(){
System.out.println("Going down the road!");
}
}
class Ragtop extends Car{
// override superclass definition
public void drive(){
System.out.println("Top down!");
super.drive();
System.out.println("Got the radio on!");
}
}
class JoyRide{
private Car myCar;
private void park(Car auto){
myCar = auto;
}
private Car whatsInTheGarage(){
return myCar;
}
public void letsGo(){
park(new Ragtop());
}
}
Car auto = new Car();
auto.drive();
System.out.println("--------");
auto = new Ragtop();
auto.drive();
System.out.println("--------");
// checking type casting of variable with polymorphic types
//Ragtop funCar;
Car hymerle = new Car();
//funCar = (Ragtop) hymerle; //runtime error
hymerle.drive();
System.out.println("--------");
hymerle = new Ragtop();
Ragtop funCar = (Ragtop) hymerle; //works bc hymerle is Ragtop
funCar.drive();
System.out.println("--------");
}
}