Constructor parameters
Description
Constructors can accept initial values.
Explanation
Their name matches the class and they have no return type.
Example
Student(String name) { this.name = name; }← Chapter 6 — Object-Oriented Programming
mixed
A constructor runs when an object is created. It initializes the object so it begins in a valid, useful state.
The this keyword refers to the current object. It is commonly used to distinguish a field from a parameter with the same name.
Constructors can accept initial values.
Their name matches the class and they have no return type.
Student(String name) { this.name = name; }this refers to the current object.
this.name selects the field instead of the parameter.
this.score = score;If you write any constructor, Java no longer creates the no-argument constructor automatically. Add one explicitly only when your design needs it.
public class ConstructorDemo {
static class Student {
String name;
int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
}
public static void main(String[] args) {
Student aditi = new Student("Aditi", 92);
System.out.println(aditi.name);
}
}