Why the getter setter functions are used in object oriented programming?

i am a java programmer but confused when the syntax of getter setter is used in java. please tell me about their function .

Newbie Asked on May 12, 2016 in Software.
Add Comment
3 Answer(s)

Tutorial is not really required for this. Read up on encapsulation

private String myField; //"private" means access to this is restricted

public String getMyField()
{
     //include validation, logic, logging or whatever you like here
    return this.myField;
}
public void setMyField(String value)
{
     //include more logic
     this.myField = value;
}
Student Answered on May 13, 2016.
Add Comment

Getter and setter methods are used to retrieve and manipulate private variables in a different class. A “getter” method does as it name suggest, retrieves a the attribute of the same name. A setter method allows you to set the value of the attribute.

Student Answered on May 13, 2016.
Add Comment

Adding Setter and Getter Methods

To make the state of the managed bean accessible, you need to add setter and getter methods for that state. The createSalutation method calls the bean’sgreet method, and the getSalutation method retrieves the result.

Once the setter and getter methods have been added, the bean is complete. The final code looks like this:

package greetings;

import javax.inject.Inject;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@Named
@RequestScoped
public class Printer {

    @Inject @Informal Greeting greeting;
    
    private String name;
    private String salutation;

    public void createSalutation() {
        this.salutation = greeting.greet(name);
    }

    public String getSalutation() {
        return salutation;
    }

    public void setName(String name) {
       this.name = name;
    }

    public String getName() {
       return name;
    }
}
Student Answered on May 13, 2016.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.