- Constructors are special method invoked when an object is created and are used to initialize them.
- A constructor can be used to provide initial values for object attributes.
- A constructor name must be same as its class name.
- A constructor must have no explicit return type.
-
Example:- public class Vehicle{ private String color; //constructor Vehicle(){ color = "Red"; } }
- The Vehicle() method is the constructor of our class , so whenever an Object of that class is created , the color attribute will be set to “Red“.
- A constructor can also take parameters to initialize attributes.
-
Example:- class Person{ private int age; public person(int mage){ age = mage; } }