Lesson 27 of 34

Encapsulation: private, Getters and Setters

9 min 35 XP

Make fields private so code outside the class can't change them directly. A getter reads the value; a setter changes it after checking it. This is encapsulation, one of the four pillars of OOP.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

The four pillars of OOP: Encapsulation, Inheritance, Polymorphism and Abstraction. Be ready to give an example of each in interviews.

Challenge

+35 XP

Write class Student with private int age (starting at 18), setAge(int age) that accepts only 1 to 100 (otherwise it prints "Invalid age" and keeps the old value), and getAge(). In main(), read a number, call setAge, then print "Age: " + getAge(). Input: 150 Output: Invalid age Age: 18

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.