Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How getter and setter are different from normal functions?

private String gg;
public void setgg(String gg) 
  {
   this.gg = gg; 
  } 
public String getgg()
  {
    return gg;
  }

Considering the above code, setter and getters are use to act on the private members of a class.

question1. If setter takes one more parameter it will not be a setter I guess ?

question2. How they are different for normal public member functions setting the values of private data members ?

I know we can implement validation in setters to for reusable code and throw exceptions but still not able to understand the real purpose

like image 514
nr5 Avatar asked Dec 15 '22 19:12

nr5


2 Answers

question1. If setter takes one more parameter it will not be a setter I guess ?

It would be setting the value, But it wouldn't be the standard setter method that many framework is looking for to set the value

question2. How they are different for normal public member functions setting the values of private data members ?

They are normal public member methods with standard naming convention


See

  • JavaBeans Spec
like image 64
jmj Avatar answered Dec 28 '22 06:12

jmj


Getters and setters are simply an object oriented convention. A lot of frameworks will look for methods called "getX()" and "setX(type)"

They're no different from any other method, but adding or removing anything from the method header will break the convention.

like image 22
Jonathon Ashworth Avatar answered Dec 28 '22 05:12

Jonathon Ashworth