
Inheritance in Java for Beginners: Complete Guide with Examples and Real-Life Explanation
Inheritance is one of the core ideas in object-oriented programming. It allows one class to use the properties and behavior of another class. In simple terms, inheritance helps us create a new class based on an existing class. The existing class is called the base class or parent class, and the new class is called the derived class or child class.
What is the purpose of inheritance?
Suppose we are building a system for a school. We create a class called “Employee” that contains common information like name, ID, and salary. Now, we want to create a “Teacher” class. Instead of writing all the properties again, we let the “Teacher” class inherit from the “Employee” class. This way, Teacher automatically gets all the common features from Employee. We can then add teacher-specific features like subject or department. This is called code reusability. We do not repeat code unnecessarily, and we build a more organized structure where each class plays its specific role.
Basic syntax of inheritance
In Java, inheritance is declared using the keyword extends. Here is the general format:
class Base {
// members of base class
}
class Derived extends Base {
// members of derived class
}
The extends keyword means that the derived class will inherit all public and protected members from the base class.
Simple example of inheritance
class Employee {
String name;
int id;
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("ID: " + id);
}
}
class Teacher extends Employee {
String subject;
void displayTeacher() {
displayInfo();
System.out.println("Subject: " + subject);
}
}
public class Main {
public static void main(String[] args) {
Teacher t = new Teacher();
t.name = "Dr. Afzal";
t.id = 101;
t.subject = "Computer Science";
t.displayTeacher();
}
}
In this example, Teacher is inheriting from Employee. The Teacher class gets access to the name and id fields, and also to the displayInfo function. It also has its own field called subject and a function called displayTeacher.
How constructors behave in inheritance
Constructors are special methods that are automatically called when an object is created. In inheritance, when a derived class object is created, the base class constructor runs first.
class Employee {
Employee() {
System.out.println("Employee constructor called");
}
}
class Teacher extends Employee {
Teacher() {
System.out.println("Teacher constructor called");
}
}
public class Main {
public static void main(String[] args) {
Teacher t = new Teacher();
}
}
Output:
Employee constructor called
Teacher constructor called
Multiple Inheritance in Java
Java does not support multiple inheritance with classes. However, it can be achieved using interfaces.
Example using interfaces:
interface Person {
void setName(String n);
}
interface Worker {
void setHours(int h);
}
class Engineer implements Person, Worker {
String name;
int hoursWorked;
public void setName(String n) {
name = n;
}
public void setHours(int h) {
hoursWorked = h;
}
void display() {
System.out.println("Name: " + name);
System.out.println("Hours Worked: " + hoursWorked);
}
}
public class Main {
public static void main(String[] args) {
Engineer e = new Engineer();
e.setName("Ali");
e.setHours(40);
e.display();
}
}
In this program, the class Engineer implements both Person and Worker interfaces. It gains the ability to store a name and number of hours worked, then display both using its own method.
Access specifiers and inheritance
Java has four main access specifiers:
public: accessible everywhereprotected: accessible in the same package and subclassesprivate: accessible only within the same class- (default): accessible within the same package
In public inheritance, public and protected members of the base class are accessible in the derived class.
Real-life analogy to summarize
Think about vehicles. You have a base class called Vehicle. It has functions like start() and stop(). Now you create a derived class called Car. It automatically gets start() and stop(), but it may also have its own function openSunroof(). Similarly, a Truck class may have its own function loadCargo(). This is how we build specialized classes from a general one.
Another example: Person and Student
class Person {
String name;
int age;
void showPerson() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
class Student extends Person {
int rollNumber;
void showStudent() {
showPerson();
System.out.println("Roll Number: " + rollNumber);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.name = "Sara";
s.age = 20;
s.rollNumber = 1234;
s.showStudent();
}
}
Inheritance allows you to create a new class that can reuse the features of an existing class. It helps in making your code more organized, more reusable, and easier to manage. You can use inheritance to model real-world relationships where one entity is a specialized version of another. A Teacher is an Employee. A Student is a Person. An Engineer is both a Person and a Worker. These examples help map real-world understanding into Java code.
25 thoughts on “Inheritance in Java for Beginners: Complete Guide with Examples and Real-Life Explanation”
**mindvault**
mindvault is a premium cognitive support formula created for adults 45+. It’s thoughtfully designed to help maintain clear thinking
**prostadine**
prostadine is a next-generation prostate support formula designed to help maintain, restore, and enhance optimal male prostate performance.
**sugarmute**
sugarmute is a science-guided nutritional supplement created to help maintain balanced blood sugar while supporting steady energy and mental clarity.
**glpro**
glpro is a natural dietary supplement designed to promote balanced blood sugar levels and curb sugar cravings.
**prodentim**
prodentim an advanced probiotic formulation designed to support exceptional oral hygiene while fortifying teeth and gums.
**vittaburn**
vittaburn is a liquid dietary supplement formulated to support healthy weight reduction by increasing metabolic rate, reducing hunger, and promoting fat loss.
**synaptigen**
synaptigen is a next-generation brain support supplement that blends natural nootropics, adaptogens
**zencortex**
zencortex contains only the natural ingredients that are effective in supporting incredible hearing naturally.
**yu sleep**
yusleep is a gentle, nano-enhanced nightly blend designed to help you drift off quickly, stay asleep longer, and wake feeling clear.
**nitric boost**
nitric boost is a dietary formula crafted to enhance vitality and promote overall well-being.
**glucore**
glucore is a nutritional supplement that is given to patients daily to assist in maintaining healthy blood sugar and metabolic rates.
**wildgut**
wildgutis a precision-crafted nutritional blend designed to nurture your dog’s digestive tract.
**breathe**
breathe is a plant-powered tincture crafted to promote lung performance and enhance your breathing quality.
**boostaro**
boostaro is a specially crafted dietary supplement for men who want to elevate their overall health and vitality.
**pinealxt**
pinealxt is a revolutionary supplement that promotes proper pineal gland function and energy levels to support healthy body function.
**prostabliss**
prostabliss is a carefully developed dietary formula aimed at nurturing prostate vitality and improving urinary comfort.
**potent stream**
potent stream is engineered to promote prostate well-being by counteracting the residue that can build up from hard-water minerals within the urinary tract.
**hepatoburn**
hepatoburn is a premium nutritional formula designed to enhance liver function, boost metabolism, and support natural fat breakdown.
**hepato burn**
hepato burn is a potent, plant-based formula created to promote optimal liver performance and naturally stimulate fat-burning mechanisms.
**cellufend**
cellufend is a natural supplement developed to support balanced blood sugar levels through a blend of botanical extracts and essential nutrients.
**prodentim**
prodentim is a forward-thinking oral wellness blend crafted to nurture and maintain a balanced mouth microbiome.
**flowforce max**
flowforce max delivers a forward-thinking, plant-focused way to support prostate health—while also helping maintain everyday energy, libido, and overall vitality.
**revitag**
revitag is a daily skin-support formula created to promote a healthy complexion and visibly diminish the appearance of skin tags.
**neurogenica**
neurogenica is a dietary supplement formulated to support nerve health and ease discomfort associated with neuropathy.
**memory lift**
memory lift is an innovative dietary formula designed to naturally nurture brain wellness and sharpen cognitive performance.