Encapsulation
- It refers to the bundling of data and methods that operate on that data, into a single unit called an object.
- The internal representation and implementation of the data are hidden from external entities, which promotes data integrity and protects it from accidental or unauthorized modifications.
- We can include encapsulation in our code by:
- Keeping instance variables protected (with an access modifier, often private).
- Making public accessor methods, and force calling code to use those methods rather than directly accessing the instance variable.
- It is not necessary to make the getters and setters for every private variable.
class Encapsulate {
private String topperName;
private String topperRollNo;
private int passingOutYear;
public void setTopperName(String topperName) {
this.topperName = topperName;
}
public String getTopperName() {
return this.topperName;
}
public void setTopperRollNo(String topperRollNo) {
this.topperRollNo = topperRollNo;
}
public String getTopperRollNo() {
return this.topperRollNo;
}
public void setPassingOutYear(int passingOutYear) {
this.passingOutYear = passingOutYear;
}
public int getPassingOutYear() {
return this.passingOutYear;
}
}
class ShellClass {
public static void main(String[] args) {
Encapsulate dbuu2020 = new Encapsulate();
dbuu2020.setTopperName("Mohammad Arham Khan");
dbuu2020.setTopperRollNo("20BTCSE0078");
dbuu2020.setPassingOutYear(2024);
System.out.println("Gold medalist UTU: " + dbuu2020.getTopperName() + "\nAdmission number: " + dbuu2020.getTopperRollNo() + "\nPassed in the year: " + dbuu2020.getPassingOutYear());
}
}
Comments
Post a Comment