Powered by Blogger.

Java : Definition of Overloading Constructors and Program Solution in Java

Definition of Overloading Constructors:-

We can declare several constructors with different arguments in a class, which is overloading constructors.

Constructor Overloading in Java:-

Here, you will learn more about Constructor and how constructors are overloaded in Java. This section provides you a brief introduction about the Constructor that are overloaded in the given program with complete code absolutely in running state i.e. provided for best illustration about the constructor overloading in Java.

Constructors are used to assign initial values to instance variables of the class. A default constructor with no arguments will be called automatically by the Java Virtual Machine (JVM). Constructor is always called by new operator. Constructor are declared just like as we declare methods, except that the constructor don't have any return type. Constructor can be overloaded provided they should have different arguments because JVM differentiates constructors on the basis of arguments passed in the constructor.

Whenever we assign the name of the method same as  class name. Remember this method should not have any return type. This is called as constructor overloading.

We have made one program on a constructor overloading, after going through it the concept of constructor overloading will get more clear. In the example below we have made three overloaded constructors each having different arguments  types so that the JVM can differentiates between the various constructors.

Overloading Constructor Program:-

 public class Light{
    int a, b, c;

    public Light(){
       a=2;
       b=4;
       c=6;
    }

    public Light(int a){
       this.a=a;
       b=4;
       c=6;
    }

    public Light(int a, int b){
       this.a=a;
       this.b=b;
       c=6;
    }

    public Light(int a, int b, int c){
       this.a=a;
       this.b=b;
       this.c=c;
    }
  }

0 comments:

Post a Comment