Java OOP Tutorial · Chapter 4 of 10
Constructors
Initialize objects safely.
A constructor runs when you create an object with new.
Use constructors to require important values such as name and course.
Constructor sample
Try it Yourself »
public class Main {
public static void main(String[] args) {
Student first = new Student("Ana Santos", "BSCS");
Student second = new Student("Ben Cruz", "BSIT");
first.introduce();
second.introduce();
}
}
Student.java
public class Student {
private String name;
private String course;
public Student(String name, String course) {
this.name = name;
this.course = course;
}
public String getName() {
return name;
}
public String getCourse() {
return course;
}
public void introduce() {
System.out.println("Hello, I am " + name + " from " + course + ".");
}
public void displayProfile() {
System.out.println("Name: " + name);
System.out.println("Course: " + course);
}
}
Classroom Tips
- this.field refers to the object field.
- Provide required values in the constructor parameters.