Java Constructors
A constructor runs when an object is created and sets it up. It has the same name as the class and no return type. Fields are usually private, with getters and setters for access.
ExampleJava
public class Main {
static class Person {
private String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
String getName() { return name; }
int getAge() { return age; }
void birthday() { age++; }
}
public static void main(String[] args) {
Person p = new Person("Ada", 36);
p.birthday();
System.out.println(p.getName() + " is now " + p.getAge());
}
}Output
Ada is now 37
this refers to the current object, which is how this.name = name tells the field apart from the parameter. private keeps the data safe: outside code can only use the methods you provide.
Quick check
What does the private keyword do to a field?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.