Inheritance with an Example in Java

In this class, We discuss Inheritance with an Example in Java.

The reader should have prior knowledge of the class and object. Click Here.

We take an example and understand the concept of Inheritance.

Example:

class A

{

int k;

void add()

{

System.out.println(“hello”);

}

}

Class B extends A

{

int j;

void use()

{

add()

System.out.println(k);

}

}

class test

{

public static void main(String args[])

{

B ob = new B();

ob.use();

ob.add();

}

}

We use the keyword extends for Inheritance.

Class B is extending class A.

class B inherits the properties of class A.

class B can use the members of class A.

In the use method, we are using the add method from class A.

Real-life examples to understand Inheritance better.

Take the tax system in India.

If the annual income is greater than 70000, we need to pay tax.

Example:

Take salary of an employee is 10000 per month.

The annual salary is 120,000.

120000 – 70000 = 50000.

The employee has to pay tax for 50000.

Suppose the annual salary is between 70000 and 150000. then 10 percent tax.

Annual salary between 150000 and 300000, then 20 percent tax.

Annual salary greater than 300000 then 30 percent tax.

The below diagram shows the complete program.

We take a class, “tax,” and write the method “taxdeduction”.

Now any organization has to apply the same logic to tax deductions.

Suppose we are running a school. We inherit the class tax.

We inherit the class “tax” if we run a supermarket.

In real life inheritance concept helps us a lot.