0

I am not able to understand the concept of making variables private as we can access them outside the class using getter and setter methods.

So how these private variable remain private.

Rashwan L
  • 38,237
  • 7
  • 103
  • 107
odesh009
  • 3
  • 2
  • Because you want control access to the values and the way in which they changed – MadProgrammer Dec 06 '15 at 05:56
  • Please search on SO before posting a question, the answer may have already been given long ago. – Erwin Bolwidt Dec 06 '15 at 05:56
  • "So how these private variable remain private." The `private` access means that no code outside of the class can access them. The getters and setters are not code outside of the class! OTOH, if you want the methods to be "private" in some *stronger* sense than is meant by the `private` keyword ... don't declare those getters / setters. – Stephen C Dec 06 '15 at 06:34

2 Answers2

0

In Java getters and setters are completely ordinary functions. The only thing that makes them getters or setters is convention. A getter for foo is called getFoo and the setter is called setFoo. In the case of a boolean, the getter is called isFoo. They also must have a specific declaration as shown in this example of a getter and setter for name:

class Dummy
{
private String name;

public void Dummy() {}

public void Dummy(String name) {
    this.name = name;
}

public String getName() {
    return this.name;
}

public void setName(String name) {
    this.name = name;
}
}

The reason for using getters and setters instead of making your members public is that it makes it possible to change the implementation without changing the interface. Also, many tools and toolkits that use reflection to examine objects only accept objects that have getters and setters. JavaBeans for example must have getters and setters as well as some other requirements.

Also, Declaring instance variables private is required so that different parts of the program cannot access them directly or modify them by mistake which could result in disaster in real world programs.

Consider reading Why Use Getters and Setters?

Adil
  • 817
  • 1
  • 8
  • 27
-1

Because then no one from other class delete tchem and often even changed they value but they still can know theyre value.

gabi 13
  • 17
  • 2
  • I'm not sure this response makes much sense. Please consider reading [Why use getters and setters?](https://stackoverflow.com/questions/1568091/why-use-getters-and-setters) – code_dredd Dec 06 '15 at 06:02