-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDemo.java
More file actions
48 lines (37 loc) · 928 Bytes
/
Demo.java
File metadata and controls
48 lines (37 loc) · 928 Bytes
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
package upcastingvsdowncasting;
class Parent {
String name;
void method()
{
System.out.println("Method from Parent");
}
}
// Child class
class Child extends Parent {
int id;
@Override
void method()
{
System.out.println("Method from Child");
}
}
public class Demo {
public static void main(String[] args)
{
// Upcasting
Parent p = new Child();
p.name = "Java upcast and downcast testing";
// This parameter is not accessible
// p.id = 1;
System.out.println(p.name);
p.method();
// Trying to Downcasting Implicitly
// Child c = new Parent(); - > compile time error
// Downcasting Explicitly
Child c = (Child)p;
c.id = 1;
System.out.println(c.name);
System.out.println(c.id);
c.method();
}
}