Encapsulation in Java is a fundamental concept of object-oriented programming that helps in bundling the data (variables) and methods (functions) that operate on the data into a single unit known as a class. It restricts direct access to some of an object's components, which can prevent the accidental modification of data. In Java, encapsulation is achieved using access modifiers like private, protected, and public.
By using encapsulation, we can control the visibility of the class's data and methods, thus improving the security and maintainability of the code.
public class Student {
// Private variables
private String name;
private int age;
// Public method to set name
public void setName(String name) {
this.name = name;
}
// Public method to get name
public String getName() {
return name;
}
// Public method to set age
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
// Public method to get age
public int getAge() {
return age;
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.setName("John Doe");
student.setAge(20);
System.out.println("Name: " + student.getName());
System.out.println("Age: " + student.getAge());
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?