Parameterised constructor in java
In Java, a parameterized constructor is a constructor that accepts one or more parameters when an object of a class is created. These parameters are used to initialize the object's instance variables with specific values.
Here's how you define and use a parameterized constructor:
1. Define the Constructor: Declare a constructor with parameters inside your class. This constructor will specify what values need to be provided when creating an object of the class.
2. Use Parameters to Initialize Instance Variables: Inside the constructor, use the parameters to initialize the instance variables.
Here's an example of a class with a parameterized constructor:
In this example, the Person
class has a parameterized constructor that takes two parameters: name
and age
. These parameters are used to initialize the name
and age
instance variables.
You can create an object of thePerson
class and pass values for the constructor parameters like this:
Person person1 = new Person("Alliya", 30);
In this case, person1
is an instance of the Person
class with the name
set to "Alliya" and the age
set to 30.
Parameterized constructors are useful when you want to ensure that objects are created with specific initial values. They allow you to provide initial data when constructing objects, making your classes more flexible and versatile.
package Tutorial_01;
public class Person {
String name;
int age;
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Other methods and fields can follow...
public static void main(String[] args) {
// TODO Auto-generated method stub
Person person1 = new Person("Alliya", 30);
System.out.println(person1.name); // Outputs Alliya
System.out.println(person1.age); // Outputs 30
}
}