riven

Riven

Riven

Java inheritances with example

Inheritances is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit properties and behaviors (fields and methods) from another class. This promotes code reuse, modularity, and easier maintenance. In Java inheritances helps establish a hierarchical relationship between classes.

What is Inheritance?

Inheritances allows one class (subclass or derived class) to inherit fields and methods from another class (superclass or base class). The subclass can also add new fields and methods or override existing ones.

Key Features of Inheritance

  1. Code Reusability: Inheritances allows new classes to use the functionality of existing classes without rewriting code.
  2. Method Overriding: Subclasses can provide specific implementations of methods that are already defined in their superclasses.
  3. Polymorphism: Inheritances enables polymorphism, allowing methods to be called on objects of different classes in a uniform way.
  4. Hierarchical Classification: Inheritances helps model real-world relationships, making it easier to represent complex structures.

Types of Inheritances in Java

Java supports several types of inheritances:

  1. Single Inheritances: A class inherits from one superclass.
  2. Multilevel Inheritances: A class inherits from another class, which in turn inherits from a third class.
  3. Hierarchical Inheritances: Multiple classes inherit from a single superclass.
  4. Multiple Inheritances (through Interfaces): Java does not support multiple inheritance directly through classes to avoid ambiguity, but it can be achieved using interfaces.

Single Inheritances

In single inheritances, one class inherits from one superclass.

Example of Single Inheritances

				
					class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat(); // Inherited method
        dog.bark(); // Method from Dog class
    }
}
//output
This animal eats food.
The dog barks.
				
			

Multilevel Inheritances

In multilevel inheritances, a class inherits from another class, forming a chain.

Example of Multilevel Inheritances

				
					class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

class Puppy extends Dog {
    void weep() {
        System.out.println("The puppy weeps.");
    }
}

public class Main {
    public static void main(String[] args) {
        Puppy puppy = new Puppy();
        puppy.eat(); // Inherited from Animal
        puppy.bark(); // Inherited from Dog
        puppy.weep(); // Method from Puppy class
    }
}
//output
This animal eats food.
The dog barks.
The puppy weeps.
				
			

Hierarchical Inheritances

In hierarchical inheritances, multiple classes inherit from a single superclass.

Example of Hierarchical Inheritances

				
					class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

class Cat extends Animal {
    void meow() {
        System.out.println("The cat meows.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        Cat cat = new Cat();

        dog.eat(); // Inherited from Animal
        dog.bark(); // Method from Dog

        cat.eat(); // Inherited from Animal
        cat.meow(); // Method from Cat
    }
}
//output
This animal eats food.
The dog barks.
This animal eats food.
The cat meows.
				
			

Multiple Inheritance (through Interfaces)

Java does not allow multiple inheritance with classes to avoid ambiguity. However, it can be achieved through interfaces.

Example of Multiple Inheritance with Interfaces

				
					interface CanFly {
    void fly();
}

interface CanSwim {
    void swim();
}

class Duck implements CanFly, CanSwim {
    public void fly() {
        System.out.println("The duck flies.");
    }

    public void swim() {
        System.out.println("The duck swims.");
    }
}

public class Main {
    public static void main(String[] args) {
        Duck duck = new Duck();
        duck.fly(); // Method from CanFly
        duck.swim(); // Method from CanSwim
    }
}
//output
The duck flies.
The duck swims.
				
			

Accessing Superclass Members

Using the super Keyword

The super keyword is used to access members (fields and methods) of the superclass.

Example of Using super

				
					class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    void eat() {
        super.eat(); // Calling the superclass method
        System.out.println("The dog eats dog food.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat(); // Calls Dog's eat method
    }
}
//output
This animal eats food.
The dog eats dog food.
				
			

Method Overriding

Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The method in the subclass must have the same name, return type, and parameters.

Example of Method Overriding

				
					class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog(); // Upcasting
        myDog.sound(); // Calls Dog's sound method
    }
}
//output
Dog barks
				
			

Abstract Classes and Inheritance

An abstract class cannot be instantiated and can contain abstract methods (methods without implementation) that must be implemented by subclasses.

Example of Abstract Classes

				
					abstract class Animal {
    abstract void sound(); // Abstract method
}

class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog(); // Upcasting
        myDog.sound(); // Calls Dog's sound method
    }
}
//output
Dog barks
				
			

Best Practices for Using Inheritance

  1. Favor Composition over Inheritance: Use composition to achieve flexibility and avoid tight coupling.
  2. Keep Class Hierarchies Simple: Avoid deep inheritance hierarchies, as they can lead to complex and hard-to-maintain code.
  3. Use Abstract Classes and Interfaces Wisely: Use abstract classes when you have a base class that should not be instantiated, and use interfaces when you want to define a contract for multiple classes.
  4. Document Your Code: Clearly document the relationships between classes, especially in complex inheritance scenarios.

Common Pitfalls

  1. Diamond Problem: This occurs when two classes inherit from the same superclass, and a subclass inherits from both. Java resolves this issue through interfaces, but it can still lead to ambiguity.

  2. Inappropriate Use of protected: Using protected can expose fields and methods to unintended classes, potentially breaking encapsulation.

  3. Overusing Inheritance: Avoid using inheritance for classes that do not share a common behavior or state. Consider using interfaces or composition instead.

  4. Ignoring final Keyword: If a class is declared as final, it cannot be subclassed. Be cautious with the use of the final keyword if you want to allow future extensions.

Recent topic

Encapsulation in java
Java Encapsulation Encapsulation is one of the four fundamental Object-Oriented Programming (OOP) concepts,...
File handling in java
File handling in java with example File handling in Java refers to the process of reading from and writing...
Java Memory Management
Java Memory Management Java Memory Management is an essential aspect of Java programming that involves...
Java exception handling
Java exception handling Exception handling is a crucial aspect of Java programming that enables developers...
Annotations in java
Annotations in java with example Annotations in Java are a powerful feature that allows developers to...
Configuration in spring
Configuration in spring Spring configuration refers to the process of setting up beans and their dependencies...
Java try-catch block
Java try-catch blocks Java is designed with a robust exception handling mechanism that helps manage errors...
parallel stream in java
Parallel Stream in java Parallel streams automatically split the source data into multiple chunks and...
AWT panel in java
What is AWT Panel in Java? A Panel in Java refers to an instance of the JPanel class, which is part of...
Spring framework in java
Spring Framework in java with example The Spring Framework is an open-source application framework for...