-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolymorphism.java
More file actions
40 lines (33 loc) · 1.17 KB
/
Polymorphism.java
File metadata and controls
40 lines (33 loc) · 1.17 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
public class Polymorphism {
// This class demonstrates the concept of polymorphism in Java.
// Method overloading: same method name with different parameters
public void display(int number) {
System.out.println("Displaying integer: " + number);
}
public void display(String text) {
System.out.println("Displaying string: " + text);
}
// Method overriding: subclass provides a specific implementation of a method
public static void main(String[] args) {
Polymorphism polymorphism = new Polymorphism();
// Demonstrating method overloading
polymorphism.display(10); // Calls the method with int parameter
polymorphism.display("Hello, Polymorphism!"); // Calls the method with String parameter
// Demonstrating method overriding
Animal animal = new Dog(); // Upcasting
animal.sound(); // Calls the overridden method in Dog class
}
}
// Base class
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}
// Subclass
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}