What is the use of getter and setter - java

Suppose we want to set a value of int y to 5 we generally do y=5;
int y=0;
y=5;
But if we use getter and setter than we do in following way
public class x {
private int y;
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
and after that we create object of x and call its method
x x1=new x();
x1.setY(5);
My question is if we can directly set y=5 then why the use getter and setter methods

Yes you can do direct access of the data member of the class but as per the OOPS concept the data needs to be encapsulated inside an object and we should use interfaces around the data to access it. As data is private attribute of particular object we define getters and setters as interfaces to access that data. Getters and Setter also provide a medium to hide the details of data storage and can come handy if u want to process data before every get or set operation which you cannot do by accessing the variable directly.

If you want to have control over what values can be set use setter.
How about
cat.weight = 0
vs
cat.setWeight(0);
and in setter you can check if weight have appropriate value
public void setWeight(int weight){
if(weight > 0){
this.weight = weight;
}
else{
// SHOUT I dont want my cat to die
}
}

It is mostly for safety reasons in computing.
You always declare class variables as private variables and you can't change them for outside with x=5;.
But with the setters and getters you can achieve this.

The real point of getters and setters is that you should only use them where they are appropriate, and that they can do more than just get and set fields.
You can have only a getter. Then the property is read only. This
should actualy be the most common case.
You can have only a setter, making the property configurable, but
communicating that nothing else should depend on its value
A getter can compute a value from several fields rather than return
one field.
A getter can make a defensive copy
A getter can perform an expensive fetch operation lazily and use a
field to cache the value
A setter can do sanity checks and throw IllegalArgumentException
A setter can notify listeners of changes to the value
All of these things are implementation details that are hidden behind the simply "getter and setter" interface. That's what encapsulation is about.

What you're asking about is one of the fundamental ideas in OOP. There's really a ton of reasons that will become a lot more obvious the more programming you do.
Encapsulation tutorial

Setters and getters are used as a part of best practices in Object-oriented programming.
Some steps to follow are:
Mark all your instance variables as private.
Expose setters and getters
In your setter method, allow setting of value only after you validate the input.
By following this, you can ensure that the variables are not set to erroneous and invalid inputs.
You can have a call to validate() method in your setter, and have the logic of validating the input in that method.

That's a long, long conversation to be had.
I'll just point you in the right direction here, but you need to work this out for yourself to really understand and internalize it.
One reason is that getters and setters allow you to protect yourself. You control what happens when the variable is modified.
You could, for example, decide to refuse some values - maybe your field needs to be a positive int, say. You cannot trust callers to respect that constraint (rule 1 of programming, do not trust anyone) and need to enforce it, possibly with an assertion.
A setter allows you to validate the value before actually modifying it. Direct access lets callers put illegal values in your class outside of your control - and since it can happen, it will happen.
Another reason is abstraction: if you expose the field, you're stuck with your representation forever. You might find a better, more optimal representation later, but you cannot change it since you've given callers direct access to your field - they now rely on its type.
Hiding the implementation details behind getters and setters, on the other hand, allows you to change your internal representation without breaking your external contracts - just modify the getter and no one ever needs to know.

This is most often used in object-oriented programming, keeping up with the concept of encapsulation. By keeping member variables of a class private, you can hide them and keep them from being affected by other code.
You can only modify those variables using a public member function. Setting up this interface and hiding the data or details makes it easier to read code.
You can read more here: http://en.wikipedia.org/wiki/Mutator_method

Related

Difference between using a method in a class to return a value and referencing the exact value itself

Let's say I have a separate GUI class that has a public boolean called "guiWait" and also has a boolean method that returns guiWait.
What's the difference between:
while(gui.guiWait)...
and
while(gui.getGuiWait())...
The difference is visibility. When you make guiWait public to be used like the first example, outside callers can modify the value. If you use a method and make the variable private, callers cannot modify the guiWait variable (although they can modify the object it references if it's mutable). Furthermore, if you make a habit of using getters and setters, then later on if you need to add logic to the getting or setting process (such as you need to make the value derived from some other new field), you already have the methods and won't break any caller's code by making the variable private. So it's considered "best practice" to always use getters and setters in Java.
If guiWait is a public boolean, there is no point in having a "getter" method for it. If it were private or protected, then it'd be a different story. The private-getter method is more flexible because you can change the implementation of the "getting" of that variable, and add checks or whatever inside the method. Private getters/setters also make things clearer and establish which things should be seen by other classes and which are only meant to be used inside a single class they are apart of. If you find you do need a getter for a specific member variable (need some kind of verification or checking), which is very common, then it would be inconsistent to do it just for that variable.
The core concept of OOP is encapsulation. The getter and setter methods (eg. your getguiWait() method) are used so that nobody is able to access the internal fields of an object. This way no one else is able to set the internal fields to an inconsistent/abnormal value. By using the "getter" and "setter" methods (and hiding the inner fields by using private), you ensure that anyone willing to set or get a field will have to go through the checks that you have put up. Example Class Cat can have age as its field. In the setter method you would check that the user input value is not negative. If you allow the age field to be public, someone could potentially set it to negative which would make no sense.
Its the pure concept of Data Encapsulation in JAVA.
A language mechanism for restricting access to some of the object's components.
A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.
http://www.tutorialspoint.com/java/java_encapsulation.htm

why we are declaring variables as private in java [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 9 years ago.
Normally in java bean classes we are declaring variables as private. Anyhow we are declaring setter and getter methods as public. Then we are able to get and set the value of property. So what is the use of declaring variable as private here? What happen if I declare as public?
Thanks in advance..
That is the purpose of encapsualtion.
Consider having an age property and you want to have some control over it. If you expose your field simply as public, you can just access it externally and do whatever you want with it. Then, checking that the age is valid can be a little bit of a hassle.
That being said, with a setter method, you could, for instance, have a verification mechanism in place. This provides you with control over how and when is your variable accessed and changed.
The same applies for getter methods. Imagine you have some internal structure you do not want to expose, say, you use enumerations internally. However, you do not want to show this outside your class. So for instance, in your getter you yield the string version of whatever value you want to yield.
You can put validation before setting value to the instance variables, like this:
class HeightBean {
private int height;
public int getHeight() {
return height;
}
public void setHeight(int height) {
if(height<0)
height=0;
this.height = height;
}
}
Most of the frameworks use bean setters and getters to access data.For example,
<jsp:useBean id="name" class="java.lang.String" scope="session">
</jsp:useBean>
<jsp:getProperty property="bytes" name="name"/>
It offers a choice. You may or may not provide getters and setters.
For instance it is a common design choice to provide only getters in case of immutable objects.
Rule of thumb: Use as less visibility as you can get away with.
The major reason for the one can be:
Restricting read and write accesses, and immutability:
If I want to make an element as read-only. I would expose the getter as public and
I can have only a setter, making the property configurable and any validation if I want to do while setting the value.
A getter can make a defensive copy.
You can have listeners associated, to notify any value change in setter method.
If one field depends on another, you can put that logic in setter method, else you will always have to write a boiler-plate code for managing that, atleast a function call would still be required. That can be moved to setter.
But having a public attribute instead of setters and getters does not give this much flexibilities. You cannot do 1 to 5 without writing extra functions and calling overheads.

Necessity of getter methods [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why use getters and setters?
This is a newbie question. Is it very much necessary to use getmethods to access property values? Once the value has been assigned, one can get the values directory. For example, in the below code, displayName() can display firstName value without the help of any getter method. Or it is a standard coding standards that one must have getter and setter method or any other methods which gives that value?
class Test{
private String firstName;
public void setName(String fname){
firstName = fname;
}
public void displayName() {
System.out.println("Your name is " + firstName);
}
}
Tell, Don't Ask is an important principle in object-oriented design. Generally you should tell objects to do things rather than ask them questions. getters/setters every where discourage this practise because you are encouraged to reach inside an object and get to the fields (or even worse reach in and poke things about in the case of setters). This breaks encapsulation and makes your code harder to reason about.
In your particular case, I'd create an object called Name that has a constructor taking the name and single method to display it.
In Your case (to display the display name) it is not neccessary to provide Getter.
But if your want use the field in another class We need to provide the Getter method.
Getter and setters are a part of the standard interface for Java Beans and many frameworks like Hibernate expect them in place. That being said it is of course up to you to decide if and when you need them and for what purpose. They provide access to your private member variables and they can even give you the chance to do more than just plain get and set.
The point of OO software is reuse. This means that other programmers, or you years from now, can use the code for other systems.
When you have private member variables, and use get/set functions, you can change the internal implementation of the function without breaking all the other code that uses it.
Do always use Getter and Setter to access your properties!
You should take a look at this article...
Having private state, encapsulation is good, and in A LOT of cases this is the right thing. Suppose that your class is suppose to be Thread Safe, having public fields you can't ensure that.
On the other hand there are cases when this is useless! Suppose that you access your object only in one package, you are sure you will never export it, then why bother?
I do not have any links to support this, but it's what I do.
I try to avoid public fields if they are not static. So I just use protected and private fields. From within the class, you can access them without get/set, that's completely fine. From outside the class, always try to use get/set.
So your example code is completely fine to me. :)
EDIT: One exception for me is if I create a struct-like container class like this
class Point4D {
public int x1, x2, x3, x4;
}
Then I think that public fields are ok. It would be still better to make them private and name the getters public int x1() etc though. As soon as some methods are introduced to this container that change the state of the instance (like changing the values of x1/x2/x3/x4), I make them private and add get/set.

What is the point of getters and setters? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why use getters and setters?
I have read books on Java, saying that it is good to create setters and getters for variables such as x and y. For example:
public int getX(){
return x;
}
public void setX(int x){
this.x = x;
}
But what is the difference from that and
...(shape.x)... // Basically getX()
and
shape.x = 90; // Basically setX()
If setters and getters are better, what practical problems would arise?
Multiple reasons:
If you allow field access like
shape.x = 90
then you cannot add any logic in future to validate the data.
say if x cannot be less than 100 you cannot do it, however if you had setters like
public void setShapeValue(int shapeValue){
if(shapeValue < 100){
//do something here like throw exception.
}
}
You cannot add something like copy on write logic (see CopyOnWriteArrayList)
Another reason is for accessing fields outside your class you will have to mark them public, protected or default, and thus you loose control. When data is very much internal to the class breaking Encapsulation and in general OOPS methodology.
Though for constants like
public final String SOMETHING = "SOMETHING";
you will allow field access as they cannot be changed, for instance variable you will place them with getters, setters.
Another scenario is when you want your Class to be immutable, if you allow field access then you are breaking the immutability of your class since values can be changed. But if you carefully design your class with getters and no setters you keep the immutability intact.
Though in such cases you have to be careful in getter method to ensure you don't give out reference of objects(in case your class have object as instances).
We can use the private variables in any package using getters and setters.
Using getter and setter functions allow for constraints and encapsulation. Lets say x is the radius. shape.x = -10 would not make much sense. Also, if someone tries to set an illegal value, you can print an error, set a default value, or do nothing.
It is good practice to make member variables private so they cannot be modified directly by programs using them.
Mutator functions
Encapsulation
A lot of people have mentioned encapsulating the specifics of the implementation, which to me is the biggest reason to use getters and setters in a class. With this, you also get a lot of other benefits, including the ability to throw out and replace the implementation on a whim without needing to touch every piece of code that uses your class. In a small project, that's not a big benefit, but if your code ends up as a well-used (internal or public) library, it can be a huge benefit.
One specific example: complex numbers in mathematics. Some languages have them as a language or framework feature, others don't. I will use a mutable class as an example here, but it could just as easily be immutable.
A complex number can be written on the form a + bi with real and imaginary parts, lending itself well to [gs]etRealPart and [gs]etImaginaryPart.
However, in some cases it's easier to reason about complex numbers on polar form re^(iθ), giving [gs]etRadius (r) and [gs]etAngle (θ).
You can also expose methods like [gs]etComplexNumber(realPart, imaginaryPart) and [gs]etComplexNumber(radius, angle). Depending on the argument types these may or may not need different names, but then the class' consumer can use either as fits its needs.
The two forms are interchangeable; you can fairly easily convert from one to the other, so which form the class uses for internal storage is irrelevant to consumers of that class. However, consumers may use either form. If you choose the form a+bi for internal representation, and expose that using fields rather than getters and setters, not only do you force the class consumers to use that form, you also cannot later easily change your mind and replace the internal representation with re^(iθ) because that turns out to be easier to implement in your particular scenario. You're stuck with the public API you have defined, which mandates that specifically the real and imaginary parts are exposed using specific field names.
One of the best reasons I can think of for getters and setters is the permanence of a class's API. In languages like python you can access members by their name and switch them to methods later. Because functions behave differently than members in java once you access a property thats it. Restricting its scope later breaks the client.
By providing getters and setters a programmer has the flexibility to modify members and behavior freely as long as the adhere to the contract described by the public API.
Another good reason to user getter and setter can be understand by the following example
public class TestGetterSetter{
private String name ;
public void setName(String name){
this.name = name ;
}
public String getName(){
return this.name ;
}
}
The point of getters and setters is that only they are meant to be used to access the private variable, which they are getting or setting. This way you provide encapsulation and it will be much easier to refactor or modify your code later.
Imagine you use name instead of its getter. Then if you want to add something like a default (say the default name is 'Guest' if it wasn't set before), then you'll have to modify both the getter and the sayName function.
public class TestGetterSetter{
private String name ;
public void setName(String name){
this.name = name ;
}
public String getName(){
if (this.name == null ){
setName("Guest");
}
return this.name ;
}
}
There is no requirement for getters and setter to start with get and set - they are just normal member functions. However it's a convention to do that. (especially if you use Java Beans)
Let's say, hypothetically, you find a library that does a better job of what you have been doing in your own class (YourClass). The natural thing to do at this point is to make YourClass a wrapper interface to that library. It still has a concept of "X" which your client code needs to get or set. Naturally, at this point you pretty much have to write the accessor functions.
If you neglected to use accessor functions and let your client code access YourClass.x directly, you would now have to rewrite all of your client code that ever touched YourClass.x. But if you were using YourClass.getX() and YourClass.setX() from the beginning, you will only need to rewrite YourClass.
One of the key concepts of programming, and especially object oriented programming, is hiding implementation details so that they're not used directly by code in other classes or modules. This way, if you ever change the implementation details (as in the example above), the client code doesn't know the difference and doesn't have to be modified. For all your client code knows, "x" might be a variable, or it might be a value that is calculated on the fly.
This is an oversimplification and doesn't cover all the scenarios where hiding implementation is beneficial, but it is the most obvious example. The concept of hiding implementation details is pretty strongly tied to OOP now, but you can find discussions of it going back decades before OOP was dreamed up. It goes back to one of the core concepts of software development, which is to take a big nebulous problem, and divide it into small well-defined problems which can be solved easily. Accessor functions help keep your small sub-tasks separate and well-defined: The less your classes know about each other's internals, the better.
There are lots of reasons. Here are just a few.
Accessors, getters in particular, often appear in interfaces. You can't stipulate a member variable in an interface.
Once you expose this member variable, you can't change your mind about how it's implemented. For example, if you see a need later to switch to a pattern like aggregation, where you want the "x" property to actually come from some nested object, you end up having to copy that value and try to keep it in sync. Not good.
Most of the time you are much better off not exposing the setter. You can't do that with public fields like x.
Before get into the answer, we gotta know something prior...! "JavaBeans".
JavaBeans are java classes that have properties. For our purpose, think of properties as private instance variables. since they're private, the only way they can be accessed
from outside of their class is through 'methods'in the class.
The methods that change a propertiy's value are called setter methods, and the methods that retrieve a property's value are called getter methods.
I would say that neither the getters/setters nor the public members are good Object Oriented design. They both break OOP Encapsulation by exposing an objects data to the world that probably shouldn't be accessing the properties of the object in the first place.
This is done by applying the encapsulation principle of OOP.
A language mechanism for restricting access to some of the object's components.
This means, you must define the visibility for the attributes and methods of your classes. There are 3 common visibilities:
Private: Only the class can see and use the attributes/methods.
Protected: Only the class and its children can see and use the attributes/methods.
Public: Every class can see and use the attributes/methods.
When you declare private/protected attributes, you are encouraged to create methods to obtain the value (get) and change the value (set). One example about visibility is the [ArrayList][2] class: it has a size property to know the actual size of the inner array. Only the class must change its value, so the code is something like
public class ArrayList<E> {
private int size;
private Object[] array;
public getSize() {
return this.size;
}
public void add(E element) {
//logic to add the element in the array...
this.size++;
}
}
In this example, you can see that the size value can change only inside the class methods, and you can get the actual size by calling it in your code (not mutating it):
public void someMethod() {
List<String> ls = new ArrayList<String>();
//adding values
ls.add("Hello");
ls.add("World");
for(int i = 0; i < ls.size(); i++) {
System.out.println(ls.get(i));
}
}
Getters and setters encapsulate the fields of a class by making them accessible only through its public methods and keep the values themselves private. That is considered a good OO principle.
Granted, it often seems like redundant code if it does nothing more than setting or returning a value. However, setters also allow you to do input validation or cleanup. Having that in one place improves data integrity for your objects,
Because we are using Object oriented programming language.
Here we are using Data hiding and encapsulation.
The variable should not directly accessible from out side world (for achiving data hiding) so we will create it private so
shape.x
is not correct.
Getter and setter method are used to get and set the value of x which is the way to achive encapsulation.

What is the definition of "accessor method"?

I've been having an argument about the usage of the word "accessor" (the context is Java programming). I tend to think of accessors as implicitly being "property accessors" -- that is, the term implies that it's more or less there to provide direct access to the object's internal state. The other party insists that any method that touches the object's state in any way is an accessor.
I know you guys can't win the argument for me, but I'm curious to know how you would define the term. :)
By accessors, I tend to think of getters and setters.
By insisting that all methods that touch the object's internal state are accessors, it seems that any instance method that actually uses the state of the object would be an accessor, and that just doesn't seem right. What kind of instance method won't use the state of the object? In other words, an instance method that doesn't use the object's state in some way shouldn't be an instance method to begin with -- it should be a class method.
For example, should the BigDecimal.add method be considered an accessor? It is a method that will read the value of the instance that the add method was called on, then return the result after adding the value of another BigInteger. It seems fairly straight forward that the add instance method is not a getter nor a setter.
An accessor method does exactly what it says on the tin: accesses some state from the type without side effects (apart from lazy instantiation, perhaps, which is not something that the caller would normally know about).
private int _age;
public int getAge()
{
return _age;
}
Methods that modify state are more usefully considered (in my opinion) as mutators.
Accessor methods : getRed, getGreen, and getBlue
These methods usually access a value.
Mutator methods : setRed, setGreen, setBlue
A mutator will mutate a value
Besides googling and wikipedia, the Java Language Specification shows this as an example of an accessor method:
private static int N;
public static int getN() { return N; }
So, yes, I'd say it just gets the value of a field. The compiler may inline this, converting it to a simple read, so anything more than that probably isn't an accessor.
I've always gone by the first definition. So, generally that applies just to getters and setters. If we go by the second method, then it's a far less useful distinction, since that covers almost all methods.
Accessor methods are used to access fields of an object. So getters and setters are both accessor methods. Observer method is the right term for a method that makes a more general observation about an object, without causing externally observable side effects. A method whose primary purpose is to cause side effects is a mutator method. Therefore, setters are an example of a mutator method. For good engineering practice, public setters should be avoided because they make it impossible for a class to enforce invariants on its data: they violate the abstraction barrier that a class should ordinarily enforce.
It is good to be able to differentiate getters and setters in technical conversation. Accessor methods are partners to modifier methods. Accessors read the state of an object (getA()), while modifiers write the state (setA(Object)).
A method that provides access (can be 'read access' or 'write access') to the internals of an object is an 'accessor method'.
The authors here certainly uses it in this manner:
http://www.javaworld.com/article/2073723/core-java/why-getter-and-setter-methods-are-evil.html
http://c2.com/cgi/wiki?AccessorsAreEvil
I think the term may originate from Common Lisp (doesn't everything?) -- with setf used to modify the value of accessor slots.

Categories