-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOverriding.java
More file actions
37 lines (33 loc) · 871 Bytes
/
Overriding.java
File metadata and controls
37 lines (33 loc) · 871 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
// Parent class
class Animal {
// Method to be overridden
public void sound() {
System.out.println("Animal makes a sound");
}
}
// Child class
class Dog extends Animal {
// Overriding the sound method of the Animal class
@Override
public void sound() {
System.out.println("Dog barks");
}
}
// Another Child class
class Cat extends Animal {
// Overriding the sound method of the Animal class
@Override
public void sound() {
System.out.println("Cat meows");
}
}
public class OverridingExample {
public static void main(String[] args) {
// Creating instances of Dog and Cat classes
Animal myDog = new Dog();
Animal myCat = new Cat();
// Calling the overridden methods
myDog.sound(); // Output: Dog barks
myCat.sound(); // Output: Cat meows
}
}