-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpcastingANDDowncasting
More file actions
72 lines (49 loc) · 1.19 KB
/
UpcastingANDDowncasting
File metadata and controls
72 lines (49 loc) · 1.19 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
class Machine{
public void start(){
System.out.println("Machine started");
}
public void start1(){
System.out.println("Machine started - start1");
}
}
class Camera extends Machine{
public void start(){
System.out.println("Camera started");
}
public void snap(){
System.out.println("Photo taken");
}
public void snap2(){
System.out.println("Photo taken snap2");
}
}
public class UpcastingANDDowncasting {
public static void main(String[] args) {
Machine mach1 = new Machine();
Camera cam1 = new Camera();
mach1.start();
cam1.start();
cam1.snap();
//Upcasting
Machine mach2 = cam1;
mach2.start();
mach2.start1();
//The variable decides which methods can be called
//this won't work. Which implementation are
//determinced by the object.
// mach2.snap();
//Downcasting -- requires brackets () with type of
//Object you're downcasting too.
Machine mach3 = new Camera();
Camera cam2 = (Camera)mach3;
cam2.start();
cam2.snap();
cam2.start1();
cam2.snap2();
//Can't be done -- causes RUNTIME error
// Machine mach4 = new Machine();
// Camera cam3 = (Camera)mach4;
// cam3.start();
// cam3.snap();
}
}