Inheritance and Polymorphism
Understanding Inheritance and Polymorphism in Java
In object-oriented programming (OOP), inheritance and polymorphism are two fundamental concepts that allow for greater flexibility, code reuse, and maintainability. These concepts are at the core of Java programming. In this article, we’ll explain what inheritance and polymorphism are, how they work in Java, and how you can apply them in your code.
1. What Is Inheritance in Java?
Inheritance is a mechanism in Java that allows one class to acquire the properties (attributes) and behaviors (methods) of another class. The class that is inherited from is called the parent class (or superclass), and the class that inherits the properties and behaviors is called the child class (or subclass).
Why Use Inheritance?
- Code Reusability: You can reuse existing code from the parent class.
- Extensibility: You can extend the behavior of a parent class in the child class.
- Simplifies Maintenance: Reduces redundancy by using a single class to define shared behaviors.
Syntax of Inheritance
In Java, a child class inherits from a parent class using the extends keyword.
class ParentClass {
// Parent class attributes and methods
}
class ChildClass extends ParentClass {
// Child class can add or override attributes and methods
}
Example:
// Parent class
class Animal {
String name;
void speak() {
System.out.println("Animal makes a sound.");
}
}
// Child class
class Dog extends Animal {
// Dog class inherits from Animal class
void speak() {
System.out.println("Dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.speak(); // Outputs: Dog barks.
}
}
In this example:
- The
Dogclass inherits thenameattribute and thespeak()method from theAnimalclass. - The
speak()method in theDogclass overrides thespeak()method in theAnimalclass to provide specific behavior for dogs.
2. What Is Polymorphism in Java?
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables one interface to be used for a general class of actions. The specific action that is performed is determined by the actual object (class) that is being referenced at runtime.
Types of Polymorphism in Java:
- Compile-time Polymorphism (Method Overloading)
This type of polymorphism is resolved during compilation. It occurs when two or more methods in the same class have the same name but differ in the number or type of parameters.Example of Method Overloading:
class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } } public class Main { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(2, 3)); // Outputs: 5 System.out.println(calc.add(2.5, 3.5)); // Outputs: 6.0 } }In this example, the
add()method is overloaded with two different parameter types, anintand adouble. - Runtime Polymorphism (Method Overriding)
This type of polymorphism is resolved at runtime and occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. This is what we call method overriding.Example of Method Overriding:
class Animal { void sound() { System.out.println("Animal makes a sound."); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks."); } } class Cat extends Animal { @Override void sound() { System.out.println("Cat meows."); } } public class Main { public static void main(String[] args) { Animal myAnimal = new Animal(); Animal myDog = new Dog(); Animal myCat = new Cat(); myAnimal.sound(); // Outputs: Animal makes a sound. myDog.sound(); // Outputs: Dog barks. myCat.sound(); // Outputs: Cat meows. } }In this example:
- The
sound()method is overridden in both theDogandCatsubclasses. - The method that is called is determined at runtime based on the actual object type (
myDogormyCat), even though both variables are of typeAnimal.
- The
3. Advantages of Polymorphism
- Flexibility: Allows you to write more generic code that can work with objects of multiple types.
- Extensibility: You can add new subclasses and behaviors without modifying existing code.
- Code Maintainability: Reduces the need to write repetitive code by using common methods that can handle various types.
4. The Relationship Between Inheritance and Polymorphism
Inheritance and polymorphism work hand-in-hand in Java.
- Inheritance allows one class to inherit the properties and methods of another, creating a hierarchy.
- Polymorphism lets objects of different classes in this hierarchy be treated uniformly, while still allowing each class to define its own behavior.
For instance, when you create an object of a subclass, it can be treated as an object of the superclass. However, the actual method that is called (if overridden) will depend on the subclass that the object belongs to, not the reference type.
Example of Inheritance and Polymorphism Together:
class Shape {
void draw() {
System.out.println("Drawing a shape.");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle.");
}
}
class Rectangle extends Shape {
@Override
void draw() {
System.out.println("Drawing a rectangle.");
}
}
public class Main {
public static void main(String[] args) {
Shape myShape = new Circle();
myShape.draw(); // Outputs: Drawing a circle.
myShape = new Rectangle();
myShape.draw(); // Outputs: Drawing a rectangle.
}
}
In this example:
myShapeis treated as aShape, but it refers to objects of typeCircleorRectangle.- The method
draw()is overridden in the subclasses, and the correct version is called based on the actual object type.
Conclusion
Inheritance and polymorphism are two key concepts in Java that enable efficient code reuse, flexibility, and scalability. With inheritance, you can create a class hierarchy and share behaviors between classes. Polymorphism, on the other hand, allows you to use the same interface to perform different actions based on the object’s actual class. Mastering these concepts will help you write cleaner, more maintainable Java code.
