A constructor is a special method created with the same name as the class name and no return type. It is used to initialize a class object.
If no constructor defined in the class, Java called a default constructor to initialize an object with default values. For example, any int variable initializes with 0 and object initialized with null.
Rules for Constructors:
- Any constructor(s) of a class must have the same name as the class name in which it resides.
- A constructor in Java cannot be static, abstract, final, and Synchronized.
- A constructor has no return type even void.
Example of Constructor in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Hello{ String name; int age; Hello(){ name="Rahul"; age=28; System.out.println("Running constructor"); } public void display() { System.out.println("Welcome " + name + ", Age " + age ); } public static void main(String args[]){ ConstDemo cdemo = new ConstDemo(); cdemo.display(); } } |