How public members of a class causes havoc in java? Can someone please explain with example? I tried to create such situation but couldn't succeed. I simply found them equivalent to 'protected' access modifier.
-
It is not necessary to declare all the member variables private or public, it depends upon the application. Read http://programmers.stackexchange.com/questions/57491/do-all-your-variables-need-to-be-declared-private – JNL Aug 23 '13 at 19:53
-
You should also see: http://stackoverflow.com/questions/215497/in-java-whats-the-difference-between-public-default-protected-and-private – Mike Aug 24 '13 at 01:45
2 Answers
It allows invalid values, breaking encapsulation.
public class Clock {
public int hours;
public int minutes;
}
Then, in unrelated code...
Clock clock = new Clock();
clock.hours = 42;
clock.minutes = 99;
Having them private with setter and getter methods allows encapsulation to enforce proper values.
public class Clock {
private int hours;
private int minutes;
public void setHours(int hours) {
if (hours < 0 || hours > 23) throw new IllegalArgumentException("bad range");
this.hours = hours;
}
// Likewise for "setMinutes" method.
}
Here's a tutorial page on encapsulation in Java on encapsulation's benefits. Quoting:
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
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.

- 176,041
- 30
- 275
- 357
-
-
1@dganesh2002 Yes, but only if you hate yourself so much. Protected fields aren't accessible from outside the boundaries of a package, meaning that no outside agent can tamper the inner gears of your class. – Fritz Aug 23 '13 at 19:35
-
1Only in subclasses, which already have the responsibility of maintaining its superclass's contract. – rgettman Aug 23 '13 at 19:35
I believe it all depends on the application/program that you design.
Declaring the members as private definitely does have advantages.
But on the other hand,
If you design say a Point Class, which the users would be inheriting and using it to draw various shapes, square, rectangle, circle, you might think of keeping the memebers x, y, z as public.
Example:
class Point{
public double x = 0.0;
public double y = 0.0;
public double z = 0.0;
}
The advantage here would be; the classes Rectangle, Square, can access the points directly
say;
class Square extends Point{
private Point p;
p.x = 4.0;
p.y = 10.0;
p.z = 0;
// Instead of using double x = p.getX(); double p.setX(5.0);
}
Hope this helps.
Read the below articles; it should help you.