0
 public class Addition
    {
        private int number1,number2;

        public void setNumber1()
        {
        }
        public int getNumber1()
        {
        }
        public void setNumber2()
        {
        }
        public int getNumber2()
        {
        }
    }

what is point of keeping variables private if i can access them using public getter and setter method.

Deepu--Java
  • 3,742
  • 3
  • 19
  • 30
  • 2
    For all answerers below (especially 3K+ users): please stop answering such obvious duplicates. Close them instead. – HamZa Mar 11 '14 at 05:57
  • 1
    @HamZa I second that. I removed my answer and voted to close. – Szymon Mar 11 '14 at 06:00

4 Answers4

0

Having a setter method allows you to implement logic prior to assigning a value to the private variable. This prevents other code from assigning arbitrary values to your private variable which might cause your object to be in an invalid state. For example:

Without setter method

public class Man {
    public int height;
}

//...some code
man.height = -1; // BOOOM!

With setter method:

public class Man {
    private int height;
    public void setHeight(int h) {
        this.height = h >= 0 ? h : 0;
    }
}

//...
man.setHeight(-10);  // Will keep the man in valid state
  • The method calling `man.setHeight(-10)` will not know that the value was not set. Then you need to change the return type to boolean to notify success/failure. And then you break the general getter setter method signature. – Subir Kumar Sao Mar 11 '14 at 06:03
0

You can add a validation in setters.

private int age;

public void setAge(int a){
   if(a>0){
      this.age = a;
   }else{
      this.age = 0;
   }
}
Isuru Gunawardana
  • 2,847
  • 6
  • 28
  • 60
0

You can assume that making a variable as private is a basic guideline for coding. If you make them public it is accessible for outside world and any one can modify it.

Suppose that number1 should always be +ve int in your case. So the setter method will have check and help you to avoid setting -ve values to it. See below:

public void setNumber1(int number)
{
    if(number >= 0)
    {
        this.number1 = number
    }
    else
    {
         //you can throw exception here
    }
}
G.S
  • 10,413
  • 7
  • 36
  • 52
  • "anyone can modify it" - not in most cases. Only you can modify it. But it's still good to stop yourself from making mistakes. – user253751 Mar 11 '14 at 06:04
0

It follows a important Object Oriented Property Encapsulation . For example I have a integer variable price with public modifier(Any one can access it)

public int price;

now we know that price can not negative but it is public so we don't have any control in this. Now see it with respect to encapsulation

private int price;
public void setPrice(int price)
{
 if(price>0)
  this.price=price
}

Here we have control, no one can set negative value of price. This is the power of Encapsulation "Giving Control".

Deepu--Java
  • 3,742
  • 3
  • 19
  • 30