-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZooDemo.java
More file actions
87 lines (70 loc) · 2.07 KB
/
ZooDemo.java
File metadata and controls
87 lines (70 loc) · 2.07 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
public class ZooDemo {
// Abstract class Animal
abstract static class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
// Abstract method
public abstract void makeSound();
// Overloaded method to make sound multiple times
public void makeSound(int times) {
for (int i = 0; i < times; i++) {
makeSound(); // Calls the makeSound() method
}
}
}
// Derived class Lion
static class Lion extends Animal {
public Lion(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println("Roar");
}
}
// Derived class Elephant
static class Elephant extends Animal {
public Elephant(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println("Trumpet");
}
}
// Derived class Monkey
static class Monkey extends Animal {
public Monkey(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println("Screech");
}
}
// Main method
public static void main(String[] args) {
// Create instances of each animal
Animal lion = new Lion("Simba");
Animal elephant = new Elephant("Dumbo");
Animal monkey = new Monkey("George");
// Store animals in an array
Animal[] zoo = {lion, elephant, monkey};
// Loop through the zoo and call makeSound methods
for (Animal animal : zoo) {
// Print the animal's name
System.out.println(animal.getName() + ":");
// Call makeSound() once
animal.makeSound();
// Call the overloaded makeSound(int) method
animal.makeSound(3);
// Print a line to separate outputs
System.out.println();
}
}
}