USING GETTER AND SETTER IN JAVA

Getters and Setters are required to protect your data from interference from outside of the class. In my previous post, you can see the class and object were in public domain. So anyone can set the value from outside of the class by just using .. So to prevent anyone from using your variable you can use getter and setter.

This is how setter and getter works. I passed variable name with datatype string as parameter to setName method. this.name=name means that whatever you pass string value to the set method, the variable Name of GetSet class would have that value that you passed in the parameter. The same works with setAge method. getName would simply return that name value.

package Lesson1;

public class GetSet {
    
        String Name;
        int Age;

    public static void main(String[] args) {
        
        GetSet student= new GetSet();
        student.setName("Danny");
        student.setAge(20);
        
        System.out.println(student.getName() + " is " + student.getAge() + " years old.");
    }
    
    public void setName(String Name) {
        this.Name=Name;
    }
    
    public void setAge(int Age) {
        this.Age=Age;
    }
    
    public String getName() {
        return Name;
    }
    
    public Integer getAge() {
        return Age;
    }
}


The output of this code when executed is as below:


Screenshot_2.png

Please note this code is not confounding one. I am still learning the Java programming and whatever I code I wrote in those inline blocks, it's for layman only so that they can easily understood the logic. Eclipse IDE allows you to automatically generate getter and setter so you don't have to take any extra hard work to write the code manually.

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center