what is the difference between `public class` and just `class`?
文章推薦指數: 80 %
public , protected and private are access modifiers. Public means that the subject may be ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams whatisthedifferencebetween`publicclass`andjust`class`? AskQuestion Asked 9years,3monthsago Modified 26daysago Viewed 98ktimes 48 24 IhavenoticedthatifIdon'twritepublicbeforeaclassitworkssameaslikeapublicclass.Ican'tunderstandwhyso?ItshouldshowanerrorwhenIdon'tdeclareaclassaspublic,privateorprotected.Butitworksfine.Whatisthereason? javaclass Share Improvethisquestion Follow editedAug25at15:59 TusharMonirul askedMay27,2013at19:14 TusharMonirulTusharMonirul 4,76499goldbadges3737silverbadges4848bronzebadges 2 1 Thiswillprovideyouanadequateanswer. – Makoto May27,2013at19:17 Youcanreferthislink,providingthesameknowledge:stackoverflow.com/questions/614818/… – Deepak Jul26,2016at13:10 Addacomment | 9Answers 9 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 48 Ihavenoticedthatifdon'twritepublicbeforeaclassitsworkssameaslikeapublicclass. Noitdoesn't.Unlessit'spublic,theclasswon'tbevisibletoothercodewhichisn'tinthesamepackage.Thedefaultaccessibility(whichcan'tbespecifiedexplicitly)isthataclass(orothermember)isonlyvisibletoothercodewithinthesamepackage. YoushouldreadtheJavaLanguageSpecificationsection6.6andtheJavaTutorial(ControllingAccesstoMembersofaClass)formoredetails. Share Improvethisanswer Follow answeredMay27,2013at19:16 JonSkeetJonSkeet 1.4m832832goldbadges89788978silverbadges90889088bronzebadges Addacomment | 42 public,protectedandprivateareaccessmodifiers.Publicmeansthatthesubjectmaybeaccessedbyanyclass,protectedbysubclass,privatebytheclassitself,nomodifiermeans"packageprotected",sothesubjectmaybeaccessedbyclassesfromthesamepackage. Subjectisclass,method,membervariable. Share Improvethisanswer Follow answeredMay27,2013at19:17 AlexRAlexR 113k1515goldbadges127127silverbadges204204bronzebadges 2 2 Ifthesubjectisa'top'levelclass,itcannnotbedeclaredaseitherprivateorprotected. – lupchiazoem Oct28,2018at1:46 Sothatwouldmeanthataprivateclasscanonlyeveroperatecompletelyindependently,right? – temporary_user_name Jan19,2019at1:10 Addacomment | 9 Classesarepackageprivatebydefault(asoutlinedhere)soit'snotbehavingthesameway.Youjustthinkitisbecauseyouhaven'ttriedtoconsumeyourclassfromadifferentpackage. Share Improvethisanswer Follow answeredMay27,2013at19:17 EstebanArayaEstebanAraya 28.8k2323goldbadges105105silverbadges139139bronzebadges Addacomment | 3 Theremustbeonlyonepublicclassper.javasourcefileandthenameofthefilemustmatchwiththispublicclass. SimilarquestionisaskedbeforeonSO.Pleasefindithere Share Improvethisanswer Follow editedMay23,2017at12:17 CommunityBot 111silverbadge answeredMay28,2013at6:28 AsadAsad 1,7971515silverbadges2323bronzebadges Addacomment | 1 Itworksthesameonlybecauseyouareworkingwithjustprobablyonefileandinthesamepackage. Ifyouhavemorethanonepackagethenyouhavetheproblem.Theclassthatdoesn'thave"public"beforethenameofclasscannotbecreatedinanotherpackage.Youcannotuseitsconstructor.Youjustcannotaccessitoutsideofthepackagethattheclasswascreatedin. Share Improvethisanswer Follow answeredJul27,2015at18:31 MorfidonMorfidon 1,30911goldbadge1717silverbadges3131bronzebadges Addacomment | 0 Fordeclarationsofclassesareavaibleonlytwokeywords: public.Example:publicclassStudent{//...} privatepackage(asdefault).Example:classNote{//...}.Itisvisibleonlyinhispackage. Youcanuseprivateandprotectedonlyifyoudeclareanmemberinsideofaclass. Example: publicclassStudent{ protectedNotenote; } Share Improvethisanswer Follow answeredMay27,2013at19:33 BlockedBlocked 32822goldbadges44silverbadges2020bronzebadges Addacomment | 0 Ifyoudon'tgiveanaccessmodifierit'sbydefaultpackageprivateaccess.Theclassisnotaccessibleoutsideofthepackage.IdeallytheJLSshould'veincludedakeywordforpackageaccesstoavoidconfusionandunintendedconsequences. Somethinglike, defaultclassStudent{} Share Improvethisanswer Follow answeredMay27,2013at20:31 The_301The_301 85111goldbadge88silverbadges1313bronzebadges Addacomment | 0 Noanormalclassandapublicclassdon'tworkthesame.Aclasswithoutaaccessmodifiersuchaspublicisautomaticallysettodefaultaccess.(No,youcan'tgivedefaultasaccessexplicitly).Ifyoucreateadefaultaccessclassinsideapackagethenthatclasscannotbeaccessedoutsidethatpackagebutpublicclasscanbeaccessedevenoutsidethatpackage Share Improvethisanswer Follow answeredMar28,2019at5:59 joejohnjoejohn 111bronzebadge Addacomment | 0 AclassnotdeclaredwithanyaccessmodifierisautomaticallydeclaredasDEFAULTatruntime Withthesetheclassisaccessiblethatsamepackage Butnotanyotherpackage Share Improvethisanswer Follow answeredJan8,2021at10:33 AbdulrazaqAbdulrazaq 11 1 1 Whiletheanswerisnotincorrect,itdoesn'taddanyvaluetotheotheranswerspublishedhere. – AlBlue Jan8,2021at11:21 Addacomment | YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedjavaclassoraskyourownquestion. TheOverflowBlog IspenttwoyearstryingtodowhatBackstagedoesforfree Aserialentrepreneurfinallyembracesopensource(Ep.486) FeaturedonMeta PlannedmaintenancescheduledforWednesday,21September,00:30-03:00UTC... RecentColorContrastChangesandAccessibilityUpdates Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew... ShouldIexplainotherpeople'scode-onlyanswers? Linked 3 What'sthedifferencebetweenpublicclassMainandclassMain? 782 InC#,whatisthedifferencebetweenpublic,private,protected,andhavingnoaccessmodifier? 5 TheuseofvisibilitymodifiersinJava 2 InnerclassvspublicinnerclassinJava Related 4190 WhatarethedifferencesbetweenaHashMapandaHashtableinJava? 2402 StaticclassvariablesandmethodsinPython 3535 Whatisthedifferencebetweenpublic,protected,package-privateandprivateinJava? 3321 WhatisaserialVersionUIDandwhyshouldIuseit? 1706 DifferencebetweenStringBuilderandStringBuffer 703 DoesPythonhave“private”variablesinclasses? 2443 What'sthedifferencebetween@Component,@Repository&@ServiceannotationsinSpring? 26615 Whyisprocessingasortedarrayfasterthanprocessinganunsortedarray? 1116 Whatisthedifferencebetweencanonicalname,simplenameandclassnameinJavaClass? 1758 Whatdoes"Couldnotfindorloadmainclass"mean? HotNetworkQuestions WhatdangersshouldIbeawareofwhendoingalong-distancebiketripthroughEurope? Howtosubtract1dayfromDateTimevalueinapex? TravellingtoNebraskaUSAfromtheUK.I’mstaying3weekswithafriend.Mybudgetissupertight:willIgetsenthome? Isitappropriatetobringaplayercharacterbackaftertheyhadbeen"killed"? Who/whataretheseentitiesinTronthatdon'tfollowthenormalpatternfor'Programs'? Iamlookingforaword(anounpreferablybutanadjectivewouldsuffice)thatdenotesapersonthatknowinglyallowsanothertousethemregularly Rolejustbelowroot? WhyDidOldSovietCityBikesHaveLongerFramesinGeneral Integrate[Sqrt[(1-Cos[t])/(Cos[a]-Cos[t])],{t,a,Pi},Assumptions->0
延伸文章資訊
- 1public class與class的區別 - 程式人生
public class與class的區別; 一個java原始檔中可以定義多個class,; 一個Java原始檔中可以沒有public class,有且只有一個。(類體,之中不能直接寫java語...
- 2java中public class與class的區別詳解 - 程式前沿
如果一個類宣告的時候使用了public class進行了宣告,則類名稱必須與檔名稱完全一致。 範例:定義一個類(檔名稱為:Hello.java) 複製程式碼程式碼如下:
- 3JAVA的封裝 - iT 邦幫忙::一起幫忙解決難題,拯救IT 人的一天
從以上的敘述,讀者可以推知這四種存取範圍的大小是public > protected > package > private。 Package的定義所謂package,可以想成是在設計或實作上相...
- 4Java Classes and Objects - W3Schools
Create a class named " Main " with a variable x: public class Main { int x = 5; }. Remember from ...
- 5Java學習之路08---方法 - iT 邦幫忙
public class Main { public static int testOne(int num){ return num + 10; } public static void tes...