复制代码
- //:Lunch.java
- //Demonstratesclassaccessspecifiers.
- //Makeaclasseffectivelyprivate
- //withprivateconstructors:
- classSoup{
- privateSoup(){}
- //(1)Allowcreationviastaticmethod:
- publicstaticSoupmakeSoup(){
- returnnewSoup();
- }
- //(2)Createastaticobjectand
- //returnareferenceuponrequest.
- //(The"Singleton"pattern):
- privatestaticSoupps1=newSoup();
- publicstaticSoupaccess(){
- returnps1;
- }
- publicvoidf(){}
- }
- classSandwich{//UsesLunch
- voidf(){newLunch();}
- }
- //Onlyonepublicclassallowedperfile:
- publicclassLunch{
- voidtest(){
- //Cantdothis!Privateconstructor:
- //!Souppriv1=newSoup();
- Souppriv2=Soup.makeSoup();
- Sandwichf1=newSandwich();
- Soup.access().f();
- }
- }///:~
欢迎光临 仓酷云 (http://ckuyun.com/) | Powered by Discuz! X3.2 |