-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolymorphismDemo.java
More file actions
61 lines (46 loc) · 1.46 KB
/
Copy pathPolymorphismDemo.java
File metadata and controls
61 lines (46 loc) · 1.46 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
//Method overloading : ping()
//Method Overriding : display()
class Parent
{
void display()
{
System.out.println("Don't get bored...with regards- Parent");
}
}
class Child extends Parent
{
void ping()
{
System.out.println("Pinged... Nothing to display");
}
void ping(String s)
{
System.out.println("Pinged... "+s);
}
void display()
{
System.out.println("Don't get bored...with regards- Child");
}
}
public class PolymorphismDemo //Class containing main() method should have the same name as that of the file.
{
public static void main(String[] args)
{
//Creating one object each of Parent and Child.
Parent p=new Parent();
Child c=new Child();
//method overloading
c.ping();
c.ping("Hey Everyone!");
System.out.println("\n\n\n");
//method overriding
c.display(); //Child display() is invoked.Child display() shadows(overrides) Parent display()
System.out.println("\n\n\n");
// Another Application of Dynamic Method Dispatch : Upcasting
Parent ref; //Creating only reference variable of Parent Class
ref=p; //ref nows stores 'p' object's reference address.So ref behaves like p.
ref.display(); //Invokes Parent's display()
ref=c; //ref nows stores 'c' object's reference address.So ref behaves like c.
ref.display(); //Invokes Child's display()
}
}