Constructors
A constructor has the class name and no return type. It runs when you use new, and it sets the starting values. this refers to the current object. If you write no constructor, Java provides an empty one.
Example
class Student {
String name;
int level;
Student(String name, int level) {
this.name = name;
this.level = level;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("Ada", 3);
System.out.println(s.name + " level " + s.level);
}
}Result
Ada level 3
Exercise
Refer to the current object.
.name = name;Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.