Java Program to add two numbers using constructor overloading


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


Main() { }

Main(int a, int b) { }


Example: How to add two numbers using constructor overloading in Java

Run it Now
import java.util.Scanner;

class Main {
    int s;
    Main() {
        System.out.print("\nThe Sum is :");
    }

    Main(int a, int b) {
        s = a + b;
    }

    void display() {
        System.out.print(s);
    }

    public static void main(String args[]) {
        int a, b;
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter Two Numbers :");
        a = sc.nextInt();
        b = sc.nextInt();

        Main t1 = new Main();

        Main t2 = new Main(a, b);
        t2.display();
    }
}

Output:

Enter Two Numbers :10 20
The Sum is :30