In the real world, you inherit traits from your parents (like eye color or height). In Java, Inheritance allows one class to acquire the properties (variables) and behaviors (methods) of another class.
Superclass (Parent): The class that gives the features.
Subclass (Child): The class that receives the features.
Imagine you are building a game. You have a Warrior class and a Mage class. Both need a name, health, and a walk()method. Instead of writing that code twice, you create a parent class called Character and let Warrior and Mage inherit from it.
Key Keyword: extends
To inherit from a class, we use the extends keyword.
The Code Example:
// 1. The Parent Class (Superclass)
class Employee {
String name;
double salary;
void work() {
System.out.println(name + " is working hard...");
}
}
// 2. The Child Class (Subclass)
// Use 'extends' to inherit from Employee
class Developer extends Employee {
String programmingLanguage;
void writeCode() {
System.out.println(name + " is writing " + programmingLanguage + " code.");
}
}
public class Main {
public static void main(String[] args) {
// Create a Developer object
Developer dev = new Developer();
// Notice we can access 'name' and 'salary' even though
// they aren't defined inside Developer!
dev.name = "Sarah";
dev.salary = 85000.00;
dev.programmingLanguage = "Java";
// Calling methods from both the Parent and the Child
dev.work(); // Inherited from Employee
dev.writeCode(); // Unique to Developer
}
}Expected Output:
Sarah is working hard...
Sarah is writing Java code.