Search

Monday, April 26, 2021

Constructor overloading in Java | Java constructor overloading example

Constructor overloading in Java


Constructor overloading in JavaIf you want to get knowledge and clear understanding about Java constructor overloading example. Then its a best place for you, here i will teach you in detail about Java constructor overloading with very easy to understand examples.


Overload Constructor in Java with Examples

In Java language, we can overload constructor just like we can overload a method. To understand constructor overloading in detail, we must first have to know about what is actually overloading in Java. In Java, methods as well as constructors both can be overloaded, which means having more than one method or constructor with the same name in same program.


Reason behind this is that using same name for methods and constructors, we can take different tasks from them. For example, we can have a method or constructor that cannot take any argument and we can have a method or a constructor with same name but can accept arguments.

We can use default constructor, constructor with single parameter, constructor with 2 parameters etc in constructor overloading to achieve different tasks but with same name.


class A

{

          A() //constructor with no argument

          {

          }

          A(int a) //constructor with one argument of type int

          {

          }

          A(int x,int y) //constructor with two argument of type int

          {

          }

          A(String name) //constructor with one argument of type String

          {

          }

}

 

Constructor Overloading Program

class A

{

 

int a,b;

          A() //Constructor without any argument

          {

                   a = 10;

                   b = 20;

                   System.out.println(a + “  “ + b);

          }

          A(int x, int y) //Constructor with 2 parameters

          {

          a = x;

          b = y;

          System.out.println(a + “  “ + b);

          }

public static void main(String ar[])

{

          A obj = new A (); //this will call the non-parameterized constructor

          A obj2 = new A (100, 200); //this will call the parameterized constructor

}

}

Output will be

10 20

100 200

 

Example Program 2

In this example, we will focus on default constructor which is actually created by Java itself when user does not write code for his own constructor in class


public class A

{

 int a;

A (int x)

{

                   a = x;

                   System.out.println(a);

}

public static void main (String ar[])

{

A object = new A (); //here we are calling a constructor which will not accept any argument and this constructor is not present in our class, so we will get error here

}

}

Output will be

        Error, because we don’t have any constructor in class which accept no argument 


Video Lectures



No comments:

Post a Comment