Encapsulation:
In Java, encapsulation refers to the bundling of data and methods that operate on that data into a single unit known as class. It provides a way to control access to the data within those objects.
Getter Methods:
- A getter method is used to retrieve the value of a private data member.
- It provides controlled access to the data by returning the value.
- The name of a getter method usually starts with "get" followed by the name of the data member it accesses (not a rule).
encapsulation.java
public int getAge() {
return age;
}
Setter Methods:
- A setter method is used to modify the value of a private data member.
- It provides a controlled access to the data by accepting a new value as a parameter.
- The name of a setter method typically starts with "set" followed by the name of the data member it modifies (not a rule).
encapsulation.java
public void setAge(int newAge) {
age = newAge;
}
Encapsulation Example:
encapsulation.java
public class Person {
private String name; // Private field
// Constructor
public Person(String name) {
this.name = name;
}
// Getter method to access the name field
public String getName() {
return name;
}
// Setter method to modify the name field
public void setName(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
// Create a Person object
Person p1 = new Person("Bob");
// Access the name field
String name = p1.getName();
System.out.println("Name: " + name);
// Modify the name field
p1.setName("Bob");
System.out.println("Name: " + p1.getName());
}
}
In this example;
- The Person class has a private data member "name" which is encapsulated.
- The constructor is initializing the value of "name".
- In main class, we create a Person object which can access public data members.
- The getName method allows you to access "name" using dot operator in main function.
- The setName method is used to set the value of "name".