2

I am new to Java...My question is

To do not access the data members outside of the class we use Access modifier, And why we are using setter methods to modify them outside of the class. Ex:-

public class Test
{

       private int a=10;
       private int b=20;
       public void sum(int x, int y)
       {
           System.out.println("Sum is:"+(x+y));
       }
       public void setA(int a)
       {
           this.a=a;
       }
       public void setB(int b)
       {
           this.b=b;
       } 
}

Like these type of cases why don't we use public members , instead of modifying them with the help of setter methods? And in which type situations we need to use setters...?

I'm unable to understand that..Somebody please help me

Thanks

cowls
  • 24,013
  • 8
  • 48
  • 78

6 Answers6

4

It's called encapsulation. Mutator methods ensure that fields are modified in an expected and controlled manner.

mre
  • 43,520
  • 33
  • 120
  • 170
3

Because your requirements might change.

public void setA(int a)
{
    if (a >= 0) {
        this.a=a;
    }
}

If you had just used a public member, you'd have to change your code everywhere that the value of a is set. If you use a setter method, your code only has to change in one place.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • In the real world, you do this and you break more code than you fix, to the point where everyone stares in astonishment what were you thinking. This violates the Principle of Least Astonishment. Sure, there may just be that one case where you can actually get away with it, but this can't possibly justify writing all those thousands upon thousands getters and setters. – Marko Topolnik Feb 12 '13 at 14:48
  • @MarkoTopolnik In the real world, requirements change. If you're worried about PLA, deprecate the setA method and provide another, appropriately named setter. If you'd rather duplicate code in thousands of places, be my guest. – Bill the Lizard Feb 12 '13 at 15:03
  • I just speak from practical experience---such a requirement never, ever, came around. If it ever did, however, I would **then** introduce a separate validating method, and change all the places where it is called for. In net effect I'd have much less to code. In practice bean validation is a separate concern, taken care of by a separate mechanism, not sprinkled around in setters. Setters **set**, that's their concern and a good architecture keeps it that way. – Marko Topolnik Feb 12 '13 at 15:52
0

Benefits of Encapsulation:

  1. The fields of a class can be made read-only or write-only.
  2. A class can have total control over what is stored in its fields.
  3. The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.

A simple use case:

You wanted to keep minimum a only:

private int a;

public void setA(int a) {
    if(this.a > a)
         this.a = a;
}

Then you changed your mind and wanted to keep maximum a:

public void setA(int a) {
    if(this.a < a)
         this.a = a;
}

If you have not used setA() method, then you had to update each place you have tried to set a new value to a. But if you have used setA(), then you don't need to touch any other place but the setter method.

Please take a look at similar questions:

What are the uses of getter/setters in Java?

Community
  • 1
  • 1
ogzd
  • 5,532
  • 2
  • 26
  • 27
  • please tell whether my understanding is correct about the points that u have mentioned. – user2064884 Feb 13 '13 at 05:47
  • please tell whether my understanding is correct about the points that u have mentioned. 1) if we have written only setter methods without getters then it becomes write only, if we write only getters without setters then it becomes readonly. 2) Because we are able to control the access through methods. we have control over fields of class. 3) I did not understand about changing of that field data type.. how can we change? if we change how does that not affect other classes which are using these data? – user2064884 Feb 13 '13 at 06:04
  • You are right about 1 and 2. In 3, I wanted to tell about the example I give. – ogzd Feb 13 '13 at 06:59
  • sorry i did not get... what about the third point? – user2064884 Feb 14 '13 at 08:33
  • Think about the use case I gave, If you had that written in multiple parts of your code, then whenever you want to modify it, you have to change every part. With using a `setter` method, you don't need to update your whole code space when you want to change the behaviour. – ogzd Feb 14 '13 at 08:50
0

According to OOP, you should always use private attributes to encapsulate information and make sure that another programmer or object is going to affect any method functionality due to bad manipulation of a variable, for example:

   private int a=10;
   private int b=20;
     public void div()
          {
                  System.out.println("Div is:"+(a/b));
           }
      public void setA(int a)
             {
                         this.a=a;
            }
     public void setB(int b)
           {
                  if(b!=0)
                    this.b=b;
           } 

For example, in this case the setter validates (i should throw an error or something) that no 0 will be saved as attribute because if it happens, it will damage the div method.

So bassically, you use setters when you need to protect the data on attributes or you wanna make sure that any value saved in the attributes, won't affect the functionality/methods inside the object.

p.d: Sorry for my english.

Skatox
  • 4,237
  • 12
  • 42
  • 47
0

In a classical biology experiment, a group of monkeys is tempted to grab a banana, resulting in a cold shower for everyone. They soon stop trying. Gradually the monkeys are replaced by newcomers and each rookie learns the hard way not to touch the banana: by receiving a round of kicks and bites from the veterans. Soon no original member is left; nobody present has actually witnessed the cold shower and in fact the mechanism has long been turned off. However, rookies still get beaten up for trying to eat the bananas.

In our story the bananas are the public fields, and monkeys are all around you. Uncritically shunning public fields is not a best practice; it's a religious practice. There is a standard barrage of "arguments" to support it, but none of them holds universally. To name a few:

  1. "the requirements may change"—the requirements on a pure data object's setter never change; it is one of the purest examples of stable API. In a business logic setting, the getters/setters on a domain model must never do anything more than pure getting/setting because they are used in many different contexts, including testing, and there must be no surprises. All concerns other than retaining a set value are handled outside the getter/setter code;

  2. "the internal representation may change"—the best way to store an int is in an int, a String in a String, and so on. There never arises a real situation where this wouldn't be true;

  3. "public fields break encapsulation, the postament of OOP"—with public getters and setters there is no effective encapsulation, it's a formality with no real-life effect;

  4. "public fields prevent instrumenting/advising by framework code"—just take a look at Hibernate: it allows public fields on an equal footing with getters/setters. It is a solved problem in modern Java.

You can use direct field access in each case where the class in question is only of local use and not exposed as a public API. Also, if a class represents pure data, in many cases it is OK to use public fields even in a public API. For example, see GridBagConstraints in the Java standard library.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • A lot of public `java.awt` classes (Point, Dimension) exposed internal state. This is generally considered a design flaw and is something to be avoided, not emulated. – Bill the Lizard Feb 12 '13 at 16:27
  • @BilltheLizard Apparently the designers of SWT didn't agree with that sentiment---they *emulated*. – Marko Topolnik Feb 12 '13 at 16:36
  • @BilltheLizard I've googled around and nowhere do I find support for your "generally considered"---all I find is strong arguments at both sides. For example, [see here](http://stackoverflow.com/questions/1568091/why-use-getters-and-setters). – Marko Topolnik Feb 12 '13 at 16:50
  • 1. That looks rather one-sided to me. 2. Read *Effective Java*. – Bill the Lizard Feb 12 '13 at 17:00
  • @BilltheLizard 1. Obviously you ignored the answers that don't suit your opinion. 2. I read it a whole decade ago. I suppose you may mean Item 13 in 2nd Edition; however a public member is as public whether it is a method or a field. I am, of course, in favor of keeping stuff as private as the design will allow; nothing to do with this subject, however, where it's dead obvious that we're discussing public API. – Marko Topolnik Feb 12 '13 at 17:50
  • Right, right. If someone disagrees with you, obviously they're the one ignoring the facts, not you. Look at the votes on the answers and tell me that it's not a one-sided argument. – Bill the Lizard Feb 12 '13 at 18:02
  • @BilltheLizard If all you want to argue for is what side the popular vote lies with, then we have no dispute. However, popular vote is not exactly a driver of progress. By popular vote our lives are controlled by a bearded apelike entity that hovers up in the skies. – Marko Topolnik Feb 12 '13 at 18:07
  • In conclusion, you have downvoted an answer for failing to reflect the opinion of the majority. Well done, Bill, you are a hero of this site. – Marko Topolnik Feb 13 '13 at 10:53
  • I downvoted an answer because I think it doles out bad advice. It has nothing to do with majority opinion. – Bill the Lizard Feb 13 '13 at 12:04
0

Attributes of the class ( a and b in your case ) describes the state of your Object. So its a good practice in OOP to make state as private and access them only through public methods.

You can access private attributes only if there is a public setter/getters. So this gives you flexibility as well as option to restrict access (if required).

rai.skumar
  • 10,309
  • 6
  • 39
  • 55