日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > java >内容正文

java

Effective Java 英文 第二版 读书笔记 Item 14:In public classes,use accessor methods,not public fields...

發(fā)布時(shí)間:2023/12/13 java 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Effective Java 英文 第二版 读书笔记 Item 14:In public classes,use accessor methods,not public fields... 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本章主要分析 公開屬性與私有屬性提供公開get、set方法兩種方式對(duì)比

?

// Degenerate classes like this should not be public! class Point { public double x; public double y; }

?

?

// Public class with exposed immutable fields - questionable 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; } ... // Remainder omitted }

Certainly, the hard-liners are correct when it comes to public classes:

if a class?is accessible outside its package, provide accessor methods, to preserve the

flexibility to change the class’s internal representation. If a public class exposes its
data fields, all hope of changing its representation is lost, as client code can be distributed
far and wide.

如果我們直接公開域,我們將無(wú)法對(duì)屬性進(jìn)行限制,這樣會(huì)導(dǎo)致,在調(diào)用該處的代碼都要添加上限制,而修改次數(shù)隨著調(diào)用的次數(shù)而增加,

如果我們提供get,set方法,就能容易的在set方法內(nèi)對(duì)傳入?yún)?shù)進(jìn)行限制。

轉(zhuǎn)載于:https://www.cnblogs.com/linkarl/p/5663952.html

總結(jié)

以上是生活随笔為你收集整理的Effective Java 英文 第二版 读书笔记 Item 14:In public classes,use accessor methods,not public fields...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。