×

Java Programs

Java Practice

Java program to implement constructor overloading

Learn how to implement constructor overloading in Java?
Submitted by Nidhi, on March 21, 2022

Problem statement

In this program, we will create a Sample class and implement constructor overloading. If we implement more than one constructor in a class, is known as constructor overloading.

Source Code

The source code to implement constructor overloading is given below. The given program is compiled and executed successfully.

// Java program to implement constructor 
// overloading

class Sample {
  int num1;
  int num2;

  Sample() {
    num1 = 10;
    num2 = 20;
  }

  Sample(int n1, int n2) {
    num1 = n1;
    num2 = n2;
  }

  void printValues() {
    System.out.println("Data members: ");
    System.out.println("Num1: " + num1);
    System.out.println("Num2: " + num2 + "\n");
  }
}

class Main {
  public static void main(String args[]) {
    Sample obj1 = new Sample();
    Sample obj2 = new Sample(30, 40);

    obj1.printValues();
    obj2.printValues();
  }
}

Output

Data members: 
Num1: 10
Num2: 20

Data members: 
Num1: 30
Num2: 40

Explanation

In the above program, we created a Sample class and public class Main. The Sample class contains data members num1, num2, and a default constructor, a parameterized constructor, a method printValues(). Here, we can use both constructors to initialize members by implementing constructor overloading.

The Main class contains a static method main(). The main() is an entry point for the program. Here, we created 2 objects obj1, obj2 and initialized objects using created constructors. After that, we called the printValues() method to print values of data members.

Java Class and Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.