Encapsulation
Description
Keep data and its rules together.
Explanation
Private fields with public methods protect valid object state.
Example
private int score;← Chapter 6 — Object-Oriented Programming
mixed
Object-oriented programming organizes code around objects and their responsibilities. Its four commonly taught ideas are encapsulation, inheritance, polymorphism, and abstraction.
These are design tools, not rules to force into every class. Use them when they make code safer, clearer, or easier to extend.
Keep data and its rules together.
Private fields with public methods protect valid object state.
private int score;Expose useful behavior and hide unnecessary detail.
A caller can use a method without knowing its internal steps.
student.study();Inheritance lets a child class reuse a parent contract, and polymorphism lets code use a parent type while different child behavior runs. Favor simple composition when inheritance does not represent a true "is a" relationship.
public class OopPrinciplesDemo {
static class Student {
private int score;
void setScore(int score) { this.score = score; }
int getScore() { return score; }
}
public static void main(String[] args) {
Student rohan = new Student();
rohan.setScore(88);
System.out.println(rohan.getScore());
}
}