Constructors in Java
Constructors in Java
Constructor in java is a special method that is automatically called when an object of a class is created. Constructor name should be similar to the class name. It cannot have a return type.
Types of Constructor
There are two types of constructor in java.
- Default constructor
- Parameterized constructor
Default constructor:
A constructor without containing any parameter that is called a Default constructor.
Example:
class ConstructorSample { ConstructorSample() { System.out.println("Constructor called"); } } class ConstructorMain { public static void main(String[] args) { ConstructorSample CS= new ConstructorSample(); } }
Output:
Constructor called
Get Prepared for Java Interviews – Click Here !
Parameterized constructor
A constructor with one or more than one parameter that is called as a Default constructor.
Example:
class Square { int side; Square(int a) { side=a; } } class AreaOfSquare { public static void main(String[] args) { Square S= new Square(7); System.out.println("Area of Square is:"+S.side*S.side); } }
Output:
Area of Square is:49
Click Here-> Get Java Training with Real-time Projects