Java Constructors
Constructors in Java is a special type of method that is used to initialize an object.
In other words, Constructor in Java is a bit of code that allows you to create objects from a class. 'New' is the keyword used to call a constructor.
Constructors In Java |
Rules for Constructors in Java
- Constructor name should match the name of the class it resides.
- Constructor must not have a return type.
- If we do not manually include a constructor, a default constructor will be automatically generated by the compiler in Java.
- Constructors invoked implicitly. i.e, invoked using the keyword 'new'.
- Constructors in Java cannot be abstract, static, final or synchronized.
Example for Default Constructor
class DemoConstructor
{
public DemoConstructor()
{
System.out.println("Default constructor");
}
}
Example for Parameterized Constructor
class DemoConstructor
{
public DemoConstructor(int num, String str)
{
System.out.println("Parameterized constructor");
}
}