Inheritance

 Inheritance



Inheritance in Java

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class to inherit the properties and methods of another class. It promotes code reusability and establishes a natural hierarchy between classes.

Basic Concepts

  1. Class: A blueprint for creating objects. It defines properties (fields) and behaviors (methods) that the objects created from the class can have.
  2. Superclass (Parent Class): The class whose properties and methods are inherited.
  3. Subclass (Child Class): The class that inherits the properties and methods from another class.

How Inheritance Works

In Java, inheritance is achieved using the extends keyword. The subclass inherits all non-private members (fields and methods) from the superclass.

public class Student {
String name;
int age;

void display1()
{
System.out.println("Name : "+name);
System.out.println("Age : "+age);
}
}
public class Teacher extends Student{
String qualification;

void display2(){
display1();
System.out.println("Qualification : "+qualification);
}
}
public class Main {
public static void main(String[] args) {
Teacher obj = new Teacher();

obj.name = "Anisul Islam";
obj.age = 30;
obj.qualification = "Bsc In CSE";
obj.display2();
}
}

Explanation

  • Inheritance: The Teacher class inherits fields and methods from the Student class, demonstrating code reusability.
  • Object Creation: An object of the Teacher class is created and its fields are set.
  • Method Invocation: The display2() method is called, which uses the inherited method display1() to print the student's details and then prints the teacher's qualification.

This example shows how inheritance allows a subclass to reuse and extend the functionality of a superclass in Java.

Types of Inheritance

  1. Single Inheritance: A class inherits from one superclass.                                                                                                 
                                                   
  2. Multilevel Inheritance: A class inherits from a subclass, creating a chain of inheritance.                                                            

  3. Hierarchical Inheritance: Multiple classes inherit from a single superclass.                                                                            

Java does not support multiple inheritance (a class cannot inherit from more than one class) directly to avoid complexity and ambiguity. However, it can be achieved through interfaces.

Access Control and Inheritance

  • public: Members are accessible everywhere.
  • protected: Members are accessible within the same package and subclasses.
  • default (no modifier): Members are accessible within the same package.
  • private: Members are not accessible outside the class.




Comments