PREV NEXT
Java Constructors:
- A constructor is a special method in a class, used to initialize the object’s fields.
- The name of the constructor is same as that of the class name.
- Whenever a new object of its class is created, a constructor is invoked.
- Every class has a constructor. Even if it is not defined, compiler would create a one implicitly.
- Constructors do not have return type.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Box { double height, width; Box() { //constructor height = 5; width = 5; } } class BoxExample { public static void main(String args[]) Box b = new Box(); //invokes the constructor } } |
- If no constructor is defined, the default constructor would initialize the instance variables to their default values (0 for numeric values, false for boolean type and null for reference types).
Parameterized Constructor:
We can also pass parameters to the constructors as we pass in methods.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Box { double height, width; Box(double h, double w) { //parameterized constructor height = h; width = w; } } class BoxExample { public static void main(String args[]) Box b = new Box(3.0,5.0); //invokes the constructor } } |
- The height and width of the Box are initialized with the values provided by the arguments passed while invoking the constructor.
- Reference types can also be passed to the constructor.
PREV NEXT