Object-Oriented Programming: Classes and Objects
A class is a blueprint; an object is a specific instance built from that blueprint. Java was designed as an object-oriented language from the ground up, so this concept underpins essentially everything else in the language.
public class Course {
private String title;
private int lessonCount;
public Course(String title, int lessonCount) {
this.title = title;
this.lessonCount = lessonCount;
}
public String getTitle() {
return title;
}
}
Course javaCourse = new Course("Java", 11);
System.out.println(javaCourse.getTitle()); // Java
Constructors
The method with the same name as the class (Course(...) above) is the constructor — it runs automatically the moment you create a new object with new, and it’s where you set up that object’s starting state. A class can have multiple constructors with different parameters, using the same overloading rules covered in the methods lesson.
Encapsulation
Fields marked private can only be read or changed through methods like getTitle() — this protects an object’s internal state from being set to something invalid from outside the class. This pattern is called encapsulation, one of the four foundational ideas of object-oriented programming (the others are inheritance, polymorphism, and abstraction, which the next lesson covers).
Getters and setters
public void setLessonCount(int lessonCount) {
if (lessonCount < 0) {
throw new IllegalArgumentException("Lesson count cannot be negative");
}
this.lessonCount = lessonCount;
}
A setter method like this can validate a new value before accepting it — something a public field could never do, since anyone could set it directly to anything, including an invalid value. This is the practical, everyday reason Java conventionally keeps fields private and exposes controlled access through methods instead.
The this keyword
this.title = title; distinguishes the object’s own title field from the constructor’s title parameter, since they share the same name — a very common and intentional pattern in Java constructors.