Can create the getter and setter method private? - Stack ...
文章推薦指數: 80 %
2) The reason that you can do it is because the Java Language Specification says ... The class properties must be accessible using get, set, ...
Home
Public
Questions
Tags
Users
Collectives
ExploreCollectives
FindaJob
Jobs
Companies
Teams
StackOverflowforTeams
–Collaborateandshareknowledgewithaprivategroup.
CreateafreeTeam
WhatisTeams?
Teams
CreatefreeTeam
CollectivesonStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
Cancreatethegetterandsettermethodprivate?
AskQuestion
Asked
10years,7monthsago
Modified
10years,7monthsago
Viewed
6ktimes
-6
0
Cancreatethesetterandgettermethodprivate?Ifyesornowhy?
java
Share
Follow
askedAug22,2011at5:39
BoomirajPBoomirajP
22922goldbadges77silverbadges1414bronzebadges
3
Youareaskingwhethergetterandsettercanbemadeprivateoryouwanttoknowthepros-andconsofmakinggetterandsettersasprivatemethods?
– Swagatika
Aug22,2011at5:41
Onlyaskingcancreatethegetterandsetterprivate?
– BoomirajP
Aug22,2011at5:43
Yes,youcan.Thereisnorestrictiononthat.
– Swagatika
Aug22,2011at5:44
Addacomment
|
5Answers
5
Sortedby:
Resettodefault
Highestscore(default)
Datemodified(newestfirst)
Datecreated(oldestfirst)
1
Generallymakingsettersasprivatemethodsisoneofthemanywaysofmakingimmutableobjects.
Share
Follow
answeredAug22,2011at5:43
SwagatikaSwagatika
3,30666goldbadges2929silverbadges3838bronzebadges
5
1
Whyevenmakeasetterthen,whenanycodethatcancallthesettercandirectlymodifytheprivatevariableaswell,andoverrideanysortofchecksthesettermightmake.
– Paul
Aug22,2011at5:48
Youwillprobablyloosethechecksthesetters/gettersmightdo,modifyingthestatevariabledirectly.Privatesetter/getteristhoughtfulsolutiononlyforthesekindsofadditionalchecks.
– panzerschreck
Aug22,2011at6:10
IfIwantedtomakeanobjectimmutable,Iwould(amongotherthings)makeitspropertiesfinal.Thenitcouldnothaveasettermethod.
– emory
Aug22,2011at7:10
@Enomy:Yeahthat'sanotherstrategyofmakingimmutableobjectsbycreatingfinalandprivatefields.
– Swagatika
Aug22,2011at8:19
Declaringallsettersprivateisnotsufficienttomakeanobjectimmutable.Ifyouhaveanysetters(publicorprivate)youalsoneedsomeschemetopreventthesetterfromchangingtheobjectstateaftertheobjectbecomesimmutable.
– StephenC
Jan16,2013at9:50
Addacomment
|
1
Cancreatethesetterandgettermethodprivate?Ifyesornowhy?
1)Yesyoucandoit.
2)ThereasonthatyoucandoitisbecausetheJavaLanguageSpecificationsaysyoucan.AsfarastheJLSisconcerned,thereisnothinglinguisticallydifferentbetweengetterandsettermethodsandanyothermethods.Andanymethodcanbedeclaredasprivate.
Yourunstatedquestioniswhyyouwoulddoit.Andthereasonissimple:tohidethemethodsfromuseoutsideoftheclass.Andwhymightyoudothat?Here'satypicaluse-case:
Wewanttocombinesomelogic(inthiscaseenforcingofaconstraint)withthesetting(orgetting)ofanattribute,butwedon'twantthesetter(orgetter)tobevisible:
publicclassFoo{
privateFooparent;//thismustnotchangeonceithasbeenset
....
privatevoidsetParent(Fooparent){
if(this.parent!=null){
thrownewSomeException(...);
}
this.parent;
}
}
Share
Follow
answeredAug22,2011at7:03
StephenCStephenC
664k9191goldbadges762762silverbadges11481148bronzebadges
Addacomment
|
0
Youcandoit,butthereishardlyapoint.Ifthosemethodsareprivatethenanycodethatcancallthosemethodscanalsoaccesstheobjectspropertiesdirectly.
Share
Follow
answeredAug22,2011at5:41
PaulPaul
135k2525goldbadges266266silverbadges256256bronzebadges
2
Iassumethatanycodethatcancallthosemethodsisundermycontrol.IchoosehowtoaccestheobjectspropertiesandIcanchoosetowriteasetter/getterconveniencemethodtosavemyselfthetroubleofrepeatingthesamecodeoverandoveragain.
– emory
Aug22,2011at7:06
Ihavecreatedacounterexample-stackoverflow.com/questions/7143564/…-wheresomecodethatcouldaccessthesetter/gettermethodscouldnotaccesstheobjectspropertiesdirectly.Admittedly,itstillseemspointless.
– emory
Aug22,2011at7:08
Addacomment
|
0
Yes,gettersandsetterscanbemadeprivate.IfyouwanttocreateaJavaBean,thenaprivategetter/setterfailstheJavaBeanscriteria,whichstates:
Theclasspropertiesmustbeaccessibleusingget,set,is(usedfor
booleanpropertiesinsteadofget)andothermethods(so-called
accessormethodsandmutatormethods),followingastandard
naming-convention.Thisallowseasyautomatedinspectionandupdating
ofbeanstatewithinframeworks,manyofwhichincludecustomeditors
forvarioustypesofproperties.
Share
Follow
answeredAug22,2011at5:49
BuhakeSindiBuhakeSindi
85.1k2727goldbadges164164silverbadges223223bronzebadges
Addacomment
|
0
Thereisnoreasonwhyyoucannotmakegettersandsettersprivate.
Whywouldyoudothis?Ifthesettermethodmodifiedapropertyindirectly.Forexample,ifyourcircleclasshadaradiusproperty,thenyoucouldhavesetRadius,setDiameter,setCircumference,setAreamethodsandyoucouldchoosetomakethesemethodsprivate.
Infact,ifyouinsertsomeconvolutedcode,youcanhavecodethatcancallthesesetter/gettermethodsthatcannotmodifythepropertiesdirectly(withoutusingreflection).Butitissufficientlyconvolutedthatitseemshardlyworththetrouble.
/**
*Thisconvolutedclasswillnotworkcorrectlyunlesstheline"this.xRef.set(x)"isline10andtheline"x=this.xRef.get();"isline23
**/
classPrivate
{
privatevoidsetX(intx)
{
try
{
this.xRef.set(x);
}
catch(IllegalAccessExceptioncause)
{
assertfalse;
}
}
privateintgetX()
{
intx;
try
{
x=this.xRef.get();
}
catch(IllegalAccessExceptioncause)
{
x=0;
assertfalse;
}
returnx;
}
privatefinalReference
延伸文章資訊
- 1Can create the getter and setter method private? - Stack ...
2) The reason that you can do it is because the Java Language Specification says ... The class pr...
- 2Java Encapsulation and Getters and Setters - W3Schools
Get and Set. You learned from the previous chapter that private variables can only be accessed wi...
- 3Java 入門指南- getter 與setter - 程式語言教學誌
屬性(field) 需要有效的封裝(encapsulation) 到物件(object) 裡頭,因此類別(class) 定義屬性時,應該宣告(declare) 為private ,也就是私有的,...
- 4Getters and Setters in Java Explained - freeCodeCamp
- 5[Java] 關於getter與setter | 羅倫斯的IT航海日誌 - - 點部落
所謂的getter以及setter是用來作為物件的私有(private)變數或. ... //set the private variable System.out.println(hello....