A constructor in Java is a special type of method that is used to initialize an object when it is created. It is automatically called when a new instance of the class is created and has the same name as the class.
For example, consider a class named “Person” with two fields “name” and “age”:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
To create a new instance of the class, we use the following code:
Person p1 = new Person("John Doe", 30);
When this code is executed, the constructor Person(String name, int age) is automatically called and the fields name and age are initialized with the values “John Doe” and 30, respectively.
Constructor Parameters
Constructor parameters are the variables or arguments passed to a constructor method in a class. These parameters are used to initialize the object’s properties or fields when it is created.
For example, consider the following class:
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
In this example, the constructor Person takes two parameters: name and age. These parameters are used to initialize the object’s properties name and age when a new Person object is created.
How To Prepare For Manual Testing Interview
- Searching for a Job vs. Being Searchable to Recruiters: Shift Your Priority!
- Software Testing Interview Questions
- Roadmap: Transition from Manual Tester to Selenium with Java Automation Tester
- How to Handle Dynamic Web Elements in Selenium: A Guide for Testers
- Manual testing interview questions for 2 years experience
- Top Mobile Testing Interview Questions and Answers (2024 – 2025)