What is Inheritance ?
- Inheritance in Java means one class(parent) inherits (gets) properties and behaviors from another class(child).
- Child object behaving as a parent object.
- It helps in reusing code, saving time, and making programs more organized.
How to achieve inheritance?
Using extends keyword.
When you go for inheritance?
There is a IS-A relationship between two classes, we go for inheritance.
Real-Life Example
Scenatio 1:
A Vehicle is a parent class.
A Car is a child class.
Vehicle has common features like speed and fuel.
Car inherits these features and can have extra features like air conditioning.
class Vehicle {
void move() {
System.out.println("Vehicle is moving");
}
}
class Car extends Vehicle {
void honk() {
System.out.println("Car is honking");
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car();
c.move();
c.honk();
}
}
Output:
Vehicle is moving
Car is honking
Scenario 2:
Employee → Developer
Employee is a general concept
Developer is a specific type of employee
---> In real life, every developer is an employee, but not every employee is a developer.
class Employee {
int id;
String name;
double salary;
void work() {
System.out.println("Employee is working");
}
}
class Developer extends Employee {
void code() {
System.out.println("Developer is writing code");
}
}
public class Company {
public static void main(String[] args) {
Developer dev = new Developer();
dev.id = 101;
dev.name = "Kumar";
dev.salary = 60000;
dev.work();
dev.code();
}
}
**Output:**
Employee is working
Developer is writing code
Why inheritance here?
- Common properties like id, name, salary belong to Employee
- Developer gets them automatically and adds its own behavior Important point:
- Car IS-A Vehicle relationship
Scenario 3:
Vehicle → Car
Vehicle is a parent (common features)
Car is a child (specialized vehicle)
---> Bike, car, bus are all vehicles.
class Vehicle {
void start() {
System.out.println("Vehicle is starting");
}
}
class Car extends Vehicle {
void playMusic() {
System.out.println("Car is playing music");
}
}
public class Transport {
public static void main(String[] args) {
Car car = new Car();
car.start(); // from Vehicle
car.playMusic(); // from Car
}
}
Why inheritance?
- Avoid rewriting common logic like start()
- Child class focuses only on extra features
Top comments (0)