首页 > 数据库技术 > 详细

Effective Java 14 In public classes, use accessor methods, not public fields

时间:2014-03-11 12:46:23      阅读:587      评论:0      收藏:0      [点我收藏+]

Principle

To offer the benefits of encapsulation you should always expose private field with public accessor method.

   

Correct Implementation

   

// Encapsulation of data by accessor methods and mutators

class Point {

private double x;

private double y;

public Point(double x, double y) {

this.x = x;

this.y = y;

}

public double getX() { return x; }

public double getY() { return y; }

public void setX(double x) { this.x = x; }

public void setY(double y) { this.y = y; }

}

   

Note

While it‘s never a good idea for a public class to expose fields directly, it is less harmful if the fields are immutable.

   

/**

* Public class with exposed immutable fields - questionable

*

* @author Kaibo

*

*/

public final class Time {

private static final int HOURS_PER_DAY = 24;

private static final int MINUTES_PER_HOUR = 60;

public final int hour;

public final int minute;

   

public Time(int hour, int minute) {

if (hour < 0 || hour >= HOURS_PER_DAY)

throw new IllegalArgumentException("Hour: " + hour);

if (minute < 0 || minute >= MINUTES_PER_HOUR)

throw new IllegalArgumentException("Min: " + minute);

this.hour = hour;

this.minute = minute;

}

   

public static void main(String[] args) {

Time t = new Time(1, 30);

t = new Time(2, 0);

System.out.println(t);

}

   

/*

* (non-Javadoc)

*

* @see java.lang.Object#toString()

*/

@Override

public String toString() {

return "Time [hour=" + hour + ", minute=" + minute + "]";

}

}

Effective Java 14 In public classes, use accessor methods, not public fields,布布扣,bubuko.com

Effective Java 14 In public classes, use accessor methods, not public fields

原文:http://www.cnblogs.com/haokaibo/p/3589780.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!