Lesson 27 of 34

Encapsulation: private, getters, settersEncapsulation: private, Getters and Setters

9 min 35 XP

Fields-ஐ private ஆக்கினால் class-க்கு வெளியிலிருந்து நேரடியாக மாற்ற முடியாது. getter மூலம் படிக்கலாம், setter மூலம் சரிபார்த்து மாற்றலாம். இதுவே encapsulation, OOP-ன் நான்கு தூண்களில் ஒன்று.

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.

OOP-ன் நான்கு தூண்கள்: Encapsulation, Inheritance, Polymorphism, Abstraction. Interview-ல் ஒவ்வொன்றுக்கும் ஒரு உதாரணம் சொல்லத் தயாராக இருங்கள்.

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

Challenge

+35 XP

Student class: private int age; setAge(int age) 1 முதல் 100 வரை மட்டும் ஏற்கும், இல்லையெனில் "Invalid age" என்று print செய்து மாற்றாது; getAge(). Age ஆரம்ப மதிப்பு 18. main()-ல் ஒரு எண்ணைப் படித்து setAge செய்து, பிறகு "Age: " + getAge() print செய்யுங்கள். Input: 150 Output: Invalid age Age: 18

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.