Write A Program In Java To Demonstrate The Constructor Overloading

0

Write A Program In Java To Demonstrate The Constructor Overloading.


Write A Program In Java To Demonstrate The Constructor Overloading


In this, we will create a java program which demonstrate the overloading concept of constructor.


Before starting the program lets understand what is constructor overloading?

Constructor overloading is a technique in java where a class can have multiple constructors with different numbers of parameters or different types of parameters. This allows you to create objects of the class in different ways.


For example, let's say we have a rectangle class that represents a rectangle with a width and height. We could have one constructor that takes no parameters and sets the width and height to default values. We could also have another constructor that takes two parameters for the width and height and sets them accordingly.


This is useful because it allows us to create objects of the rectangle class in different ways depending on what information we have available at the time of object creation.


Here's a program in java that demonstrate the constructor overloading:


Program

public class Main {
    private int num;
    private String str;

    // First Constructor With No Parameters
    public Main() {
        this.num = 0;
        this.str = "";
    }

    // Second Constructor With One Parameters
    public Main(int num) {
        this.num = num;
        this.str = "";
    }

    // Third Constructor With Two Parameters
    public Main(int num, String str) {
        this.num = num;
        this.str = str;
    }

    public int getNum() {
        return num;
    }

    public String getStr() {
        return str;
    }

    public static void main(String[] args) {
        Main obj1 = new Main();
        Main obj2 = new Main(10);
        Main obj3 = new Main(10, "Computer");

        System.out.println(obj1.getNum() + " " + obj1.getStr());
        System.out.println(obj2.getNum() + " " + obj2.getStr());
        System.out.println(obj3.getNum() + " " + obj3.getStr());
    }
}

Output
0 10 10 Computer

Explanation
In this example, we have a MyClass class with three constructors. The first constructor has no parameters and initializes the num and str fields to zero and an empty string, respectively. The second constructor takes one integer parameter and initializes the num field to the provided value and the str field to an empty string. The third constructor takes an integer and a string parameter and initializes both fields to the provided values.

In the main method, we create three MyClass objects using the different constructors and print their num and str fields to the console using the getNum and getStr methods.

❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In Java Programming.


Post a Comment

0Comments
Post a Comment (0)