- Author

- Name
- Nelson Silva
- Social
Introduction
Inheritance is one of the four pillars of object-oriented programming (OOP), alongside encapsulation, polymorphism, and abstraction. Through inheritance, it is possible to create a new class based on an existing one, allowing code reuse and the construction of hierarchical relationships.
Fundamentals of Inheritance
Benefits of Inheritance
- Code Reuse: There is no need to rewrite the same code repeatedly. The subclass inherits all members of the superclass.
- Extensibility: The existing superclass can be extended to incorporate new attributes and behaviours.
- Class Hierarchy: Establishes a hierarchical relationship between superclass and subclass.
Restrictions of Inheritance in Java
In Java, inheritance is implemented using the extends keyword. However, there are some restrictions:
- Single Inheritance: Java does not support multiple inheritance through classes. A class can only inherit from a single class.
- Constructors and Static Initialisers: These are not inherited by subclasses.
- Association Relationship: If a class inherits another, it is an "is-a" relationship. For example, if
Childis an extension ofParent, thenChildis aParent.
The protected keyword
The protected keyword in Java allows a class member to be accessed directly by any class within the same package or by subclasses. It is a way to provide more access than private, while still restricting generalised access like public.
package com.caffeinealgorithm.programaremjava;
public class Inheritance {
public void Run() {
var person = new Child();
person.information();
person.favoriteFood();
/*
Name: Nelson Silva
Age: 28
My favorite food is seafood rice.
*/
}
}
class Parent {
protected String lastName = "Silva";
public void favoriteFood() {
System.out.println("My favorite food is seafood rice.");
}
}
class Child extends Parent {
private String firstName = "Nelson";
private int age = 28;
public void information() {
System.out.printf("Name: %s %s\n", firstName, lastName);
System.out.printf("Age: %d\n", age);
}
}
Conclusion
Inheritance is a powerful tool in Java, allowing programmers to write more modular and reusable code. By understanding the fundamentals and nuances of inheritance, you will be better prepared to tackle the complex challenges of object-oriented programming in Java.