Java OOP Concepts: Inheritance and Polymorphism Examples
Single Inheritance in Java
Single inheritance involves one class inheriting properties and methods from exactly one parent class. Below is a demonstration using the Animal and Dog classes.
class Animal {
Animal() {
System.out.println("Animal constructor called");
}
void eat() {
System.out.println("I can eat");
}
}
class Dog extends Animal {
Dog() {
System.out.println("Dog constructor called");
}
void bark() {
System.out.println("I can bark");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat();
myDog.bark();
}
}Implementing Multiple Inheritance using Interfaces
Java does not support multiple inheritance of classes, but it achieves multiple inheritance of type and behavior through interfaces. A class can implement multiple interfaces, as shown below:
interface Animal {
void eat();
}
interface Mammal {
void sleep();
}
class Dog implements Animal, Mammal {
public void eat() {
System.out.println("Dog is eating.");
}
public void sleep() {
System.out.println("Dog is sleeping.");
}
}
public class Main {
public static void main(String[] args) {
Dog obj = new Dog();
obj.eat();
obj.sleep();
}
}Java Method Overloading Example
Method overloading is a form of polymorphism where multiple methods in the same class share the same name but have different parameter lists (different number or type of arguments). This is resolved at compile time.
class OverloadExample {
void display(int a) {
System.out.println("Integer: " + a);
}
void display(int a, int b) {
System.out.println("Two Integers: " + a + " and " + b);
}
void display(double a) {
System.out.println("Double: " + a);
}
public static void main(String[] args) {
OverloadExample obj = new OverloadExample();
// Calls method with one int parameter
obj.display(5);
// Calls method with two int parameters
obj.display(10, 20);
// Calls method with double parameter
obj.display(3.14);
}
}Java Method Overriding Demonstration
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. This is a key aspect of runtime polymorphism.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// Overriding the makeSound method from the Animal class
void makeSound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
myAnimal.makeSound(); // Calls Parent class method
Animal myDog = new Dog();
myDog.makeSound(); // Calls overridden method in Child class
}
}
English with a size of 3.1 KB