Getter & Setter Methods in Java

Getter & Setter Methods in Java

Getter & Setter Methods in Java

As we know, we can’t access the private variables of a class outside it. Getter & setter methods are used to access private variable of a class outside of it.

In this article we will be discussing about Getter And Setter Methods in Java.

Encapsulation in Java:

Encapsulation in Java is a process of wrapping code and data together under a  single unit. In other words, we can say that it is a process of binding a code and the data that manipulates it under the same unit. It prevents external access to the data. If a data member is private it means it can only be accessed within the same class. No outside class can access private data members of other class.

In order to access the Private Variables, you must:

  • Provide public get and set methods to access and modify the value of a private variable.
  • Declare class variables and attributes as private.

Getter:

Getter method helps us to get the value of a private variable whether it is string, int, float or char. we can get the value of private variable by using get method which is followed by that variable name.

Syntax:

public data_type getVariable_name(){
    return Variable_name;
}

Setter:

Setter method helps us to set or change the value of a private variable of a class according to its data type. we can set the value of the private variable by using set method followed by the variable name.

Syntax:

public void setVariable_name(Data_type tempvariable_name){
    this.variable_name = tempvariable_name;
}

Example:

Run
import java.io.*;

// Class Definition 
class PrepInsta{
    //Private member of the class
    private String name;
    
    //Getter function with Fisrt word of variable name is capital
    public String getName(){
        return name; 
    }
    
    //Setter Function that sets the value of the private variable
    public void setName(String temp){    
        this.name = temp;
    }
}
 
class Main{
    public static void main(String[] args){
        
        // Object of prepInsta class
        PrepInsta ob = new PrepInsta();
        
        // setting the value of the name variable
        ob.setName("Prepster");
        System.out.println(ob.getName());
    }
}
Output:

Prepster

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription