Java Inheritance
π Inheritance in Java β The Fun Way! πβ
Inheritance in Java is like getting superpowers from your parents. Imagine if you could inherit your dadβs driving skills or your momβs cooking expertiseβwell, in Java, classes can do just that! π
Inheritance is one of the four pillars of object-oriented programming (OOP), allowing child classes to acquire all the non-private goodies (properties and methods) from their parent class. Itβs like getting hand-me-downs but way more useful! ποΈ
π§ 1. What is Inheritance in Java?β
In Java, inheritance means a class (child/subclass) extends another class (parent/superclass) to inherit its properties. The magic keyword here is extends
.
public class Parent {
}
public class Child extends Parent { // The child class is extending the Parent class
}
πΆ β‘οΈ π§ Just like how a child inherits traits from their parents, Java classes do the same!
π 2. Inheritance in Actionβ
Letβs say we have an Employee
class. Every employee has basic details, but some employees (like managers) have extra perksβlike subordinates! π€΅
public class Employee {
private Long id;
private String firstName;
private String lastName;
// Getters and Setters
}
public class Manager extends Employee {
private List<Employee> subordinates;
public Manager(long id, String firstName, String lastName, List<Employee> subordinates) {
super(id, firstName, lastName);
this.subordinates = subordinates;
}
}
π Now, letβs test if our Manager
class got the employee attributes.
Manager manager = new Manager(1L, "Sujit", "Karne", List.of(new Employee(2L, "Alex", "Dave")));
System.out.println(manager);
π¨οΈ Output:
Manager{id=1, firstName='Sujit', lastName='Karne', subordinates=[Employee{id=2, firstName='Alex', lastName='Dave'}]}
Without inheritance, we would have written id
, firstName
, and lastName
in multiple placesβyuck! π€’ Code duplication = bad. Reusability = good. β
π³ 3. Types of Inheritanceβ
Java supports four types of inheritance, depending on how classes are structured.
π 3.1 Single Inheritanceβ
A single child class extends a single parent class. This is the "one kid, one parent" scenario.
class Animal {
void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Woof!");
}
}
ποΈ 3.2 Multi-level Inheritanceβ
This is like a grandparent-parent-child relationship.
class Grandparent {
void wisdom() {
System.out.println("Grandparents are wise");
}
}
class Parent extends Grandparent {
void experience() {
System.out.println("Parents are experienced");
}
}
class Child extends Parent {
void energy() {
System.out.println("Children have energy");
}
}
π³ 3.3 Hierarchical Inheritanceβ
One parent, multiple children. Imagine one powerful superhero (parent) and multiple sidekicks (children).
class Parent {
void parentMethod() {
System.out.println("Parent method");
}
}
class Child1 extends Parent {
}
class Child2 extends Parent {
}
π€Ή 3.4 Multiple Inheritance (via Interfaces)β
Java doesnβt allow multiple inheritance with classes, but we can achieve it with interfaces. Think of it as inheriting different superpowers from different sources. πͺ
interface Flyable {
void fly();
}
interface Swimmable {
void swim();
}
class Superhero implements Flyable, Swimmable {
public void fly() { System.out.println("Flying high!"); }
public void swim() { System.out.println("Swimming fast!"); }
}
NOTE: Till JDK 1.7, multiple inheritance was not possible in java. But from JDK 1.8 onwards, multiple inheritance is possible via use of interfaces with default methods.
π― 4. Accessing Parent Class Membersβ
π 4.1 Constructorsβ
To call a parent class constructor, use super()
. Remember, it must be the first statement inside the child class constructor. π¨
public class Manager extends Employee {
public Manager() {
super(); // Must be first statement
// Other statements
}
}
π 4.2 Fieldsβ
Non-private fields are inherited, but private fields? Nope! β Use getters and setters instead.
Manager manager = new Manager(...);
manager.getId();
manager.getFirstName();
manager.getLastName();
β οΈ Be careful when both parent and child have fields with the same name!
class Employee {
int rating = 100;
}
class Manager extends Employee {
int rating = 200;
}
Manager manager = new Manager();
System.out.println(manager.rating); // 200
Employee mgrEmployee = new Manager();
System.out.println(mgrEmployee.rating); // 100
Why? Because fields are accessed based on reference type! π§
π¬ 4.3 Methodsβ
Child classes can call non-private methods of the parent class.
public class Manager extends Employee {
@Override
public String toString() {
return "Manager{" +
"id=" + getId() +
", firstName='" + getFirstName() + "'" +
", lastName='" + getLastName() + "'" +
"}β;
}
}
But if both classes have a method with the same name? The method from the actual instance type is used. π
class Employee {
public int getRating() { return 100; }
}
class Manager extends Employee {
public int getRating() { return 200; }
}
Manager manager = new Manager();
System.out.println(manager.getRating()); // 200
Employee mgrEmployee = new Manager();
System.out.println(mgrEmployee.getRating()); // 200
π 5. Conclusionβ
πΉ Inheritance follows an IS-A relationship.
πΉ Child classes inherit non-private members from the parent class.
πΉ Java uses extends
for class inheritance and interfaces for multiple inheritance.
πΉ Fields are accessed from the reference type, while methods are from the instance type.
Happy Coding! π