Encapsulation in Java
Encapsulation is a fundamental concept in Java that refers to the practice of
wrapping data (variables) and methods that act on that data within a single unit, a
class. Encapsulation is used to hide the internal implementation details of a class
and prevent unauthorized access to the data.
Protecting Class Properties and Methods
In Java, encapsulation is achieved using access modifiers such as private,
protected, and public. These access modifiers determine the accessibility of class
properties and methods.
private: Only accessible within the same class
protected: Accessible within the same class, package, and subclass
public: Accessible from anywhere
Student Class Encapsulation
Here's an example of encapsulation in a Student class:
public class Student {
// private variables
private String name;
private int age;
private double gpa;
// constructor
public Student(String name, int age, double gpa) {
this.name = name;
this.age = age;
this.gpa = gpa;
}
// getter methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getGPA() {
return gpa;
}
// setter methods
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setGPA(double gpa) {
this.gpa = gpa;
}
}
In this example, the name, age, and gpa variables are declared as private to
prevent unauthorized access. Getter and setter methods are provided to access and
Encapsulation is a fundamental concept in Java that refers to the practice of
wrapping data (variables) and methods that act on that data within a single unit, a
class. Encapsulation is used to hide the internal implementation details of a class
and prevent unauthorized access to the data.
Protecting Class Properties and Methods
In Java, encapsulation is achieved using access modifiers such as private,
protected, and public. These access modifiers determine the accessibility of class
properties and methods.
private: Only accessible within the same class
protected: Accessible within the same class, package, and subclass
public: Accessible from anywhere
Student Class Encapsulation
Here's an example of encapsulation in a Student class:
public class Student {
// private variables
private String name;
private int age;
private double gpa;
// constructor
public Student(String name, int age, double gpa) {
this.name = name;
this.age = age;
this.gpa = gpa;
}
// getter methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getGPA() {
return gpa;
}
// setter methods
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setGPA(double gpa) {
this.gpa = gpa;
}
}
In this example, the name, age, and gpa variables are declared as private to
prevent unauthorized access. Getter and setter methods are provided to access and