Parameterized constructor
A constructor with one or more parameters is called as parameterized constructor.
Why parameterized constructor is used?
Parameterized constructor is used to provide the initial values to the object properties (initial state of object). By use of parameterized constructor different objects can be initialize with different data member values or states.
Example
/** * This program is used to show the use of parameterized constructor. * @author w3schools */ public class ParameterizedConstructor { int num; String str; ParameterizedConstructor (int n, String s){ System.out.println("Parameterized Constructor called."); num = n; str = s; } public static void main(String args[]){ //constructor call ParameterizedConstructor object = new ParameterizedConstructor (10, "w3schools"); //print values of object properties System.out.println("num = " + object.num); System.out.println("str = " + object.str); } } |
Output
Parameterized Constructor called. num = 10 str = w3schools |
Java interview questions on constructor
- Default constructor
- Does constructor return any value in java?
- Is constructor inherited in java?
- Can you make a constructor final in java?
- Difference between constructor and method in java?
- How to copy values from one object to another java?
- How to overload constructor in java?
- can you create an object without using new operator in java?
- Constructor chaining in java
- Parameterized constructor in java
- Can we call subclass constructor from superclass constructor?
- What happens if you keep return type for a constructor?
- What is the use of private constructor in java?
- Can a constructor call another constructor java?