DEV Community

Indumathy
Indumathy

Posted on

Inheritance

  • It is used for code reuse and to reduce the duplication.

  • Here the child object behaving as a parent Object.

  • By using "extends" keyword we can achieve inheritance.

  • When there is Is-A relationship between two class we can use inheritance.

Real time Scenario:

  • In a company employee is a common concept. Developer, Tester, HR, Admin are specific type of employee.

  • All the employee will commonly have their ID and salary detail.

  • Here we can use the ID, salary and other common data(variables) in all classes by inheritance method with the help of "extends" keyword.

Example:

package inheritance;

public class Employee {
int empid;
int salary;

public static void main(String[] args) {
    Employee hr1 = new Employee();
    hr1.work();


}
Enter fullscreen mode Exit fullscreen mode

public void work()
{
System.out.println("Emloyee");

}

}

_**USING INHERITANCE FOR DEVELOPER***_*

package inheritance;

public class Developer extends Employee {

public static void main(String[] args) {
Developer dev1 = new Developer();
dev1.empid=1;
dev1.salary=1000;
dev1.work();

System.out.println(dev1.empid);
System.out.println(dev1.salary);
Enter fullscreen mode Exit fullscreen mode

}

}

Scenario 2:

In a car showroom all the cars will have the common data like price, year,
version and owner detail. we can create variables in common Class (Vehicles) and later call the variables in another class for specific class (BMW).

Example:

package inheritance;

public class Vehicle {
int price;
int year;
double version;
String owner;

void showroom() {
    System.out.println("ABC Automobiles");
}
Enter fullscreen mode Exit fullscreen mode

}

****USING INHERITANCE FOR BMW MODEL***

package inheritance;

public class BMW extends Vehicle
{
void brand()
{
System.out.println("BMW");
}
public static void main(String[] args) {
BMW customer1 = new BMW();
customer1.price=300000;
customer1.year=2026;
customer1.version=8.0;
customer1.owner="Indumathy";
customer1.showroom();
customer1.brand();

System.out.println("Price- "+customer1.price);  
System.out.println("Manufactured- "+customer1.year);
System.out.println("Version- "+customer1.version);
System.out.println("Owner- "+customer1.owner);
}
Enter fullscreen mode Exit fullscreen mode

}

Output:

ABC Automobiles
BMW
Price- 300000
Manufactured- 2026
Version- 8.0
Owner- Indumathy

Top comments (0)