What are Getters and Setters?


I'm new to Java and I want to understand the terminology. Perhaps I already use it, but I do not know that it is called that way. I'll give you an example as I understand it, if I'm wrong, please correct it. Getter example:

viod Sum(int a, int b){
    int s=a+b;
    return s;
}

Example of a setter:

static void TxtHP(String name1, String name2){
    System.out.println(nameA1 + " любит " +name2); 
}
Author: Nicolas Chabanovsky, 2015-06-05

3 answers

Your examples are not the same at all. These are not getters or setters - they are from another planet altogether.

A getter is a method that returns the value of a certain class property, and a setter, respectively, is what sets the class property. Example:

public class MyClass {
   private String name; //свойство

   public String getName() { //геттер
      return this.name;
   }

   public void setName(String name) { //сеттер 
      this.name=name;
   }
}

There is a naming convention - a naming convention according to which the getter should be called: get<Свойство>(), and the setter set<Свойство>

Update

According to the specified naming convention, the so-called Java Beans, and there are so many already installed on these beans, for example POJO - so naming here is not just a fad, but a means of survival.

Update2

Returning to the question naming convention for Boolean properties, the naming of getters is accepted: boolean is<свойство>(), not boolean get<свойство>(), in addition, there are indexed properties (or properties in the form of arrays), for which there are 4 types getters/setters:

Foo[] getFoo();
Foo getFoo(int );
void setFoo(Foo[] );
void setFoo(int, Foo);

Original Source

 10
Author: Barmaley, 2017-11-03 11:31:16

Getter allows you to get values (read values), and setter allows you to write values to a variable. In the code, they are ordinary methods. But the method name always starts with the get or set prefix.

class someClass(){
    private int a;

    public int getA(){
       return a;
    }

    public void setA(int a){
       this.a = a
    }
}
 4
Author: katso, 2015-06-05 05:35:29

Getters and Setters this is one of the whales of OOP, namely encapsulation. They are used to gain access to private properties. Read here for full understanding.

 3
Author: Alexey Shtanko, 2015-06-05 06:53:34