Getter and Setter in java
Access modifier in java:
In java, there are four access modifiers which are default, public, private, protected. Each one of them has a specific set of accessing rules.
Default: This is the default access modifier that gets applied when no access modifier is not specified on a class or a data member. This provides accessibility within the same package.
Private: When a class has data members that can't be accessed outside the class providing the encapsulation, the private keyword is used to make a member private.
Public: Public access modifier makes the class and data members public and it is accessible within the package and in inherited classes and even in a different package of non-subclass.
Protected: It is close to private but in protected the protected data members can be accessed by the child class which is derived from it and a subclass of a different package.
Private> Default > Protected > Public
When a certain instance variable of a class is declared private it needs to be accessed in a different method, not through a subclass derived from it. hence, it is not visible outside the class. These methods are called getter and setter methods providing the encapsulation.
In the below code of class Rectangle length and width of a rectangle are declared private and needs to be accessed through setter method setLength() and setBreadth() and values should be retrieved through getLength() and getBreadth() methods.
class Rectangle{
//private members of class
private int length;
private int breadth;
//public method to set the length and breadth of rectangle
public void setLength(int l){
this.length = l;
}
public void setBreadth(int w){
this.breadth = w;
}
//public method to get the length and breadth of rectangle
public int getLength(){
return this.length;
}
public int getBreadth(){
return this.breadth;
}
public static void main(String[] args) {
Rectangle r = new Rectangle();
r.setLength(2);
r.setBreadth(4);
System.out.println("The area is" + " " + r.getLength() * r.getBreadth());
In the above code a rectangle object is created and the data members are accessed through
setter and getter methods.
I hope you guys liked this article, here are some other articles you may like:
0 Comments