Tutorials

Java OOP Tutorial

All Tutorials Learning Tools Login

Java OOP Tutorial · Chapter 6 of 10

Encapsulation

Protect fields with private access.

Make fields private and expose getters or controlled methods.

This prevents other classes from changing data in unsafe ways.

Encapsulation sample Try it Yourself »
public class Main {
    public static void main(String[] args) {
        Student student = new Student("Diego Ramos", "BSIT");

        // Use getters instead of reading private fields directly.
        System.out.println("Name: " + student.getName());
        System.out.println("Course: " + student.getCourse());
        student.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

  • Private fields + public methods is a common beginner pattern.
  • Main should not access name/course fields directly.