Introduction:
In the world of object-oriented programming, one of the key concepts that enhances code organization and promotes reusability is “inheritance.” In Java, the process by which one class acquires the properties and functionalities of another class is known as inheritance. In this blog post, we’ll delve into the fundamentals of inheritance using a practical example.
Basics of Inheritance:
1. What is Inheritance?
Inheritance is the mechanism in Java where one class, known as the child class, inherits the properties (data members) and functionalities (methods) of another class, referred to as the parent class or base class. The primary aim is to facilitate code reusability, allowing a class to focus on its unique features while leveraging the common properties and functionalities from another class.
2. Classes in the Example:
In our example, we have two classes – Teacher and InheritanceExample. The Teacher class serves as the parent class, containing properties such as college, profession, and a private variable code. The InheritanceExample class extends the Teacher class, demonstrating inheritance in action.
Example Code:
class Teacher {
// properties of the class
public String college = “ABC College”;
String profession = “Teaching”; // protected variable
private String code; // private variable can only be accessed inside the class
// method of the class
void duty() {
System.out.println(“This is duty of Parent Class”);
}
// set and get methods for the private variable
void setCode(String pCode) {
code = pCode;
}
String getCode() {
return code;
}
}
public class InheritanceExample extends Teacher {
public void main(String[] args) {
// instance variables
String name = “John”;
String department = “Physics”;
// accessing properties and methods of the parent class
System.out.println(“Name = ” + name);
System.out.println(“Profession = ” + profession);
System.out.println(“Department = ” + department);
System.out.println(“College = ” + college);
duty(); // overridden method in the child class
System.out.println();
setCode(“abc123”);
System.out.println(“Code = ” + getCode());
}
// Method Overriding: duty() method of Parent Class is overridden.
void duty() {
System.out.println(“This is duty of Child Class”);
}
}
Types of Inheritance:
Single Inheritance:
Class B extends Class A.
Multilevel Inheritance:
Class C extends Class B.
Class B extends Class A.
Hierarchical Inheritance:
Class B, Class C, and Class D extend Class A.
Multiple Inheritance (Not Supported in Java):
Class C extends Class A and Class B.
Conclusion:
Understanding inheritance is crucial for building scalable and maintainable Java applications. By grasping the concepts outlined in this example, you’ll be better equipped to design efficient and modular code that takes full advantage of the power of inheritance. Explore the various types of inheritance and incorporate these principles into your object-oriented programming endeavors.