
#java #oop #encapsulation #programming
Java Concepts I’m Mastering – Part 8: Encapsulation & Data Hiding Continuing my journey of mastering Java fundamentals. Today’s concept: Encapsulation — one of the core pillars of OOP. What is Encapsulation? Encapsulation means: Wrapping data (variables) and methods (functions) together inside a class and restricting direct access to data. It protects the internal state of an object. How Do We Achieve It? Make variables private Provide public getter and setter methods Example class Student { private String name; // Data hidden public void setName(String name) { this.name = name; } public String getName() { return name; } } Now: Student s = new Student(); s.setName("Kanishka"); System.out.println(s.getName()); Direct access like s.name is not allowed. Why is This Important? Protects data from unwanted modification Improves security Makes code more maintainable Allows validation inside setters Example with validation: public void setAge(int age) { if(age > 0) { this.age = age; } } Now in
Continue reading on Dev.to Beginners
Opens in a new tab



