Reputation: 2210
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.
Upvotes: 1
Views: 251
Reputation: 4703
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.
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.
Upvotes: 0
Reputation: 178253
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.
Upvotes: 7