Inheritance and Polymorphism
Duration: 7 min
This module delves into the core concepts of Java programming: Inheritance and Polymorphism. Understanding these concepts is crucial as they form the backbone of object-oriented programming, allowing for code reusability, method overriding, and dynamic method dispatch. Mastery of these topics is essential for any aspiring Java developer, particularly in enterprise-level applications.
Inheritance
Inheritance is a mechanism where a new class is derived from an existing class. The new class, known as the subclass or derived class, inherits attributes and methods from the existing class, known as the superclass or base class. This promotes code reusability and establishes a natural hierarchy between classes. The 'extends' keyword is used to implement inheritance in Java.
class Animal {
void eat() {
System.out.println("eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("barking");
}
}
public class Test {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
}
}eating
barkingPolymorphism
Polymorphism allows objects to be treated as instances of their parent class. It is of two types: compile-time (or static) and runtime (or dynamic). Compile-time polymorphism is achieved through method overloading, while runtime polymorphism is achieved through method overriding. This enables a single action to behave differently based on the object that it is acting upon.
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Woof");
}
}
public class Test {
public static void main(String[] args) {
Animal a;
a = new Cat();
a.makeSound();
a = new Dog();
a.makeSound(};
}
}💡 Tip: When overriding methods, always use the @Override annotation to avoid accidental method signature changes in the superclass.
❓ What does the 'extends' keyword do in Java?
❓ Which type of polymorphism is achieved through method overriding?