0

As a fresher, sometimes the question might be duplicated. I know the encapsulation and access modifier in Java. But in an interview, I was asked why most of the time variables are private and getters and setters are public. I'd like to know with some examples where I couldn't find in stackoverflow.

  • You should do some google for that but It's okay you can start with [docs.oracle](https://docs.oracle.com/javase/tutorial/java/javaOO/variables.html) – Dushyant Tankariya Jun 26 '19 at 07:45
  • 2
    because you want to be able to control how your variables can be altered – Stultuske Jun 26 '19 at 07:45
  • See: https://softwareengineering.stackexchange.com/questions/143736/why-do-we-need-private-variables, and also https://stackoverflow.com/questions/8720220/why-is-string-length-a-method/8720305#8720305 – yshavit Jun 26 '19 at 07:47
  • 2
    Suppose you want your `marks` variable between 0 and 100 only. If it's public it can be assigned any value suppose 200. On the other hand, if you make it private and provide getters and setters now you can control the value modification. You can write if else conditions in your setter and don't set any value to `marks` variable that is outside the range. – Mushif Ali Nawaz Jun 26 '19 at 07:50

1 Answers1

1

For example, take a class Person:

public class Person {
 private String name;
 private String surname;
 private int age;

 public void setAge(int age) {
   if (age < 0 ) throw new IllegalArgumentException("age cannot be negative");
   this.age = age;
 }
}

That allows you to control how variables can be changed from outside. If you would have the age variable public, you could just set the age to -50 or something else that you do not want.
You want to achieve that other users of your class cannot change variables like they want, instead you want them to stick on your "control flow". Take an complex algorithm as an example, you do not want to let the user of this set variables directly since this could destroy the functionality. Another point that might be intersting for you is that you can log changes if you have a private variable that is only setable by a public setter method.

ItFreak
  • 2,299
  • 5
  • 21
  • 45