-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicPolymorphism.java
More file actions
45 lines (40 loc) · 1.02 KB
/
DynamicPolymorphism.java
File metadata and controls
45 lines (40 loc) · 1.02 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
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Animal ani; // Creates a vaiable with the type of Animal
System.out.println("What animal do you want?");
System.out.print("1: Dog | 2: Cat = ");
int ch = sc.nextInt();
if(ch==1)
{
ani=new Dog(); // Assigned the Dog class as per choice
ani.speak();
}
else if(ch==2)
{
ani=new Cat();
ani.speak();
}
else
{ System.out.println("Invalid!!");
ani=new Animal();
ani.speak();
}
sc.close();
}
}
class Animal{
void speak()
{System.out.println("Animal *makes a sound*");}
}
class Dog extends Animal{
@Override
void speak()
{System.out.println("Dog *Barks*");}
}
class Cat extends Animal{
@Override
void speak()
{System.out.println("Cat *meows*");}
}