- 
                Notifications
    You must be signed in to change notification settings 
- Fork 17
Inheritance
        Pankaj Chouhan edited this page Sep 3, 2023 
        ·
        1 revision
      
    Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create new classes (subclasses) that inherit properties and behaviors from existing classes (superclasses). There are several types of inheritance in Java:
- 
Single Inheritance: - In single inheritance, a subclass can inherit from only one superclass.
- Java supports single inheritance for classes, which means a class can have only one direct parent class (superclass).
- This is the most common form of inheritance and ensures a simple and straightforward class hierarchy.
 class Animal { // ... } class Dog extends Animal { // ... } 
- 
Multiple Inheritance (Not Supported in Java): - Multiple inheritance allows a class to inherit properties and behaviors from more than one superclass.
- Java does not support multiple inheritance for classes due to the "diamond problem," which can result in ambiguity when resolving method calls.
- However, Java supports multiple inheritance through interfaces, where a class can implement multiple interfaces to inherit behavior from different sources.
 interface A { // ... } interface B { // ... } class MyClass implements A, B { // ... } 
- 
Multi-Level Inheritance: - In multi-level inheritance, a subclass inherits from another subclass, creating a chain of inheritance.
- Each class in the chain inherits properties and behaviors from its immediate parent class.
- This is a common form of inheritance and helps create a hierarchy of related classes.
 class Animal { // ... } class Dog extends Animal { // ... } class GermanShepherd extends Dog { // ... } 
- 
Hierarchical Inheritance: - In hierarchical inheritance, multiple subclasses inherit from a common superclass.
- Each subclass shares the properties and behaviors of the common superclass.
- This allows you to create a family of related classes.
 class Animal { // ... } class Dog extends Animal { // ... } class Cat extends Animal { // ... } 
- 
Hybrid Inheritance (Achieved through Interfaces): - Hybrid inheritance combines multiple forms of inheritance, including single inheritance, multiple inheritance (through interfaces), and hierarchical inheritance.
- In Java, you can achieve a concept similar to hybrid inheritance by using interfaces and combining single and hierarchical inheritance with interface implementation.
 interface Swimmer { void swim(); } class Animal { // ... } class Fish extends Animal implements Swimmer { @Override public void swim() { // ... } } class Dog extends Animal { // ... } 
