zoukankan      html  css  js  c++  java
  • Effective Java 14 In public classes, use accessor methods, not public fields

    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 + "]";

    }

    }

    作者:小郝
    出处:http://www.cnblogs.com/haokaibo/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    详解javascript中的闭包
    Cookie/Session的机制与安全
    session详解
    linux常用目录简介
    对比cp和scp命令 将数据从一台linux服务器复制到另一台linux服务器
    webpack打包速度和性能再次优化
    pc浏览器css和js计算浏览器宽度的差异以及和滚动条的关系
    chrome浏览器Timing内各字段解析
    深入理解-CLI与PHP-FPM
    swool教程链接汇总
  • 原文地址:https://www.cnblogs.com/haokaibo/p/in-public-classes-use-accessor-methods-not-public-fields.html
Copyright © 2011-2022 走看看