Constructor Overloading In Java programming

Java 8Object Oriented ProgrammingProgramming

Similar to method overloading, constructor loading is the creation and usage of constructors with diffrent type of arguments. We can use this operator to refer to constructors.See the example below.

Example

 Live Demo

class A {
   public int a;
   public A() {
      this(-1);
   }
   public A(int a) {
      this.a = a;
   }
   public String toString() {
      return "[ a= " + this.a + "]";
   }
}
public class Tester {
   public static void main(String args[]) {
      A a = new A(10);
      System.out.println(a);
      A a1 = new A();
   System.out.println(a1);
   }
}

Output

[ a= 10]
[ a= -1]
raja
Published on 01-Nov-2018 16:21:44
Advertisements