Within the Java paradigm there is an idea of Getters and Setters. The idea behind this is encapsulation… that is, to keep most of a class private, except for specific methods you want to expose.
For example, consider you had a class called Broker. Perhaps you don’t want all the elements in the class exposed, but you do want people to be able to get Broker names and set Broker names. So perhaps you have some brokers in the database, like FXCM, Gain Capital, etc. You have other methods in Broker such as account lookups that you want to remain private…. In this case you can create some code like so:
The code to the left is an example of setting some getters and setters.
At the top of the class a private instance variable of brokerName is set. It’s type is String.
Then there are two methods that are both public methods. The first is the setter. It is a void method because the setter doesn’t return any value when it’s called.
Below that is a getter method, that simply returns the instance variable that has been set. In this situation, we have a class called Broker that can be instantiated and brokerName will default to a null value. After instantiating the class, we could call the public methods in the class to set and get a value…
Broker broker = new Broker();
The above code would instantiate the Broker class. It will initially default the Broker Name to null. But we call a public setter method in the class to set a name for a broker. Likewise I’m printing out the brokerName via the getter method.
Unlike using the getters and setters in the above example, we can make use of a Constructor, so that the value of brokerName is set when the class is instantiated.
In the case of the constructor, I’ve removed the setter method for brokerName. Instead a constructor method is added.
This method is public, and calls the class itself with public Broker(String brokerName)…
Within the method it looks like our setter method from before. We make use of this.brokerName = brokerName;
As before we have a getter method that is a public String returning the brokerName that is being set.
How we invoke this is…..
Broker broker = new Broker(“Brian Warner”);
In the above, we omit the setter and simply use the constructor to set the instance variable value.
One thing to note here… in this case there is now a required param to be set. You can no longer just use Broker broker = new Broker(); You now have to supply the parameter String expected.
Generating Getters, Setters and Constructors
Most IDE’s will generate this code for you. For example, with the Intellij IDE you can create a class, add an instance variable and then right click in the code space and choose Generate. That will bring up a sub menu asking what you want to generate. The options will be like: Getters, Setters, Getters & Setters, Constructor. When you choose one, it will prompt you for a choice selection.
Once you choose the appropriate choice, the IDE will create the methods for you. Simple.