Constructors in Javan



Constructors are similar to methods and are different in the following sense.

  • They do not have any return type.

  • The name of the constructor is the same as the name of the class.

  • Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class.

  • Each time a new object is created, at least one constructor will be invoked.

  • A class can have more than one constructor.

Example

class A {
   public int a;
   //default constructor
   public A() {
      this(-1);
   }

   //parameterized constructor
   public A(int a) {
      this.a = a;
   }
}

public class Tester {
   public static void main(String[] args) {
      //new object created using default constructor
      A a1 = new A();        
      System.out.println(a1.a);

      //new object created using parameterized constructor
      A a2 = new A(1);        
      System.out.println(a2.a);
   }
}

Output

-1
1
Samual Sam
Samual Sam

Learning faster. Every day.


Advertisements