Java Tutorial: 6(Constructors)

All Classes in Java have constructors in them if a constructor is not defined then compiler creates a default constructor for that class.However, once you define your own constructor, the default constructor is no longer used.
It is similar to a method only but with the same name as the class name.It must not have any explicit return type.A Java constructor cannot be abstract, static, final, and synchronized.
It is a special type of method which is used to initialize the object.Every time an object is created using the new() keyword, at least one constructor is called.
Constructor in Java is of 2 types:

  1. Default Constructor(No-arg Constructor)
  2. Parameterized Constructor
Examples: 
No-arg Constructor-


Public class ClsConstructor {
   Int number;
   ClsConstructor() {
      number = 08;
   }
}

Parameterized Constructor-

Public class ParamConstructor {
   int number;
   
   ParamConstructor(int x ) {
      number = x;
   }
}


Comments