What is constructor Keyword?
Constructor is a keyword which is used in class. The name of constructor is same as class name. It is always void as it does not have any return type. Constructor is called when object is initialize. We can make various constructor but none of them should have same argument.
Each constructor initialize some or all of rectangle’s member variable. It is used in each programming language such as C, C++, Python, Java, JavaScript. It is used to initialize object with the default or initial state. In Java, if constructor is not created then default constructor is created by JVM( Java Virtual Machine).
For Example (in Java):
class A
{ A( ) //Constructor same name as class
{ System.out.println(“Hello Constructor”); }
public static void main()
{ System.out.println(“Hello main”);
A a1 = new A();
} }
Types of constructor:
There are three types of constructor-
Default constructor, Parameterized constructor, Copy constructor.
Default Constructor:
A default constructor is a constructor either has no parameters, or if it has parameters, all the parameters have default value. It is an Inline public member of its class.
For Example: class A {
A() { System.our.println(“Constructor”);
}
public static void main(){
A a= new a();
}
Output: Constructor
Parameterized Constructor:
Parameter constructor consists of parameter. Every constructor should have different data type and variable in same class otherwise it will throw an error.
Copy constructor:
When we create a constructor , in argument we write copy constructor. first we write an class name then create an object , then it forms copy constructor.