简体   繁体   中英

How public members of a class causes havoc in java?

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 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.

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.

  1. Source 1
  2. Source 2
  3. Source 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM