PSYCHOCODES

Explaining Getters and Setters in Java with Example

When you learn object-oriented programming one of the most important concepts we learn in it is Encapsulation. Encapsulation is the concept of wrapping up variables and the methods(functions) acting on them as a single unit. Encapsulation also hides the data variables from other classes these variables can be accessible to only the methods specified within the class.

To know more about object-oriented concepts read our article Explaining the Object Oriented Programming Concepts in Java

To achieve Encapsulation in Java we must remember the following points:

  • Make variables inside the class private.
  • Provide methods to access these variables inside the class these methods are commonly known as Getters and Setters.

Let's define a simple class in java with few variables and two methods for each variable for setting the value and getting the value.

class GetterSetter{
  
  private int price;
  private String product;
  
  public void setPrice(int price){
    this.price = price;
  }
  
  public int getPrice(){
    return price;
  }
  
  public void setProduct(String product){
    this.product = product;
  }
  
  public String getProduct(){
    return product;
  }
  
  
}

In the above class we created two variables of type int and String and for each variable, we have declared two methods one for Setting the value and one for getting the value.

Now, let's call these methods into our main function and see them in action.

class GetterSetter{
  
  private int price;
  private String product;
  
  public void setPrice(int price){
    this.price = price;
  }
  
  public int getPrice(){
    return price;
  }
  
  public void setProduct(String product){
    this.product = product;
  }
  
  public String getProduct(){
    return product;
  }
  
  
}
class Main{
  public static void main(String args[]){
    
    GetterSetter gs = new GetterSetter();
    gs.setPrice(1149);
    gs.setProduct("Iphone X");
    
    System.out.println("Cost of "+gs.getProduct()+" is: "+gs.getPrice());
    
  }
}

Output:

Getters and Setters in Java

In the above code, we have simply created the object of the class and called the methods to indirectly access the variables via getter() and setter(). So these were getters() and setters() hope you liked this article.

Thank you for reading.

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don't forget to subscribe to our Newsletter.

If you like this article, then please share it and help us grow.

Share your thoughts