Constructor


Constructor

To initialize an object we use a special method called as constructor. A constructor can be declared either implicitly or explicitly. If a constructor is not declared in the class then JVM builds a default constructor for that class, it is called as default constructor. A constructor name is same as the class name in which it is declared. It should not have an explicit return type. Modifiers such as abstract, static, final or synchronized are not allowed for constructor

Syntax:

className (parameter_list)
{
//code
}

There are 2 types of constructors which are demonstrated in the

Example No.1:

Com.knowledge2life public class Main { String x;; public Main() { x = "Knowledge2life"; } public static void main(String[] args) { Main myObj = new Main(); System.out.println(myObj.x); } }

OUTPUT:

Knowledge2life

Example No.2:

Com.knowledge2life public class Main { String a; public Main(String b) { a = b; } public static void main(String[] args) { Main myObj = new Main("Knowledge2life"); System.out.println(myObj.a); } }

OUTPUT:

Knowledge2life