-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path43_Dynamic Polymorphism
More file actions
60 lines (50 loc) · 1.29 KB
/
Copy path43_Dynamic Polymorphism
File metadata and controls
60 lines (50 loc) · 1.29 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
//polymorphism = many shapes/forms
//dynamic = after compilation (during runtime)
//ex. A corvette is a: corvette, and a car, and a vehicle, and an object
<Main.java>
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Animal animal;
System.out.println("What animal do you want?");
System.out.print("(1=dog) or (2=cat):");
int choice = scanner.nextInt();
if(choice==1){
animal = new Dog();
animal.speak();
}else if(choice==2){
animal = new Cat();
animal.speak();
}else{
animal = new Animal();
System.out.println("That choice was invalid");
animal.speak();
}
}
}
<Animal.java>
public class Animal {
public void speak() {
System.out.println("animal goes *brrrr*");
}
}
<Dog.java>
public class Dog extends Animal {
@Override
public void speak() {
System.out.println("dog goes *bark*");
}
}
<Cat.java>
public class Cat extends Animal {
@Override
public void speak(){
System.out.println("cat goes *meow*");
}
}
>>
What animal do you want?
(1=dog) or (2=cat): >>3
>> That choice was invalid
cat goes *brrrr*