Java Program to add two numbers using hierarchical inheritance


In this program, You will learn how to add two numbers using hierarchical inheritance in Java.


20 = 10 + 10

30 = 20 + 10


Example: How to add two numbers using hierarchical inheritance in Java

Run it Now
import java.util.Scanner;

class A {
    static int x, y, z;
    Scanner sc = new Scanner(System.in);
}

class B extends A {

    void input() {
        System.out.print("Enter two numbers :");
        x = sc.nextInt();
        y = sc.nextInt();
    }
}

class Main extends A {

    void add() {
        z = x + y;
    }

    void result() {
        System.out.println("\nSum is :" + z);
    }

    public static void main(String args[]) {
        B obj1 = new B();
        obj1.input();

        Main obj2 = new Main();
        obj2.add();
        obj2.result();
    }
}

Output:

Enter two numbers :2 3
Sum is :5