• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

More than one class in a file

 
Ranch Foreman
Posts: 911
8
  • Number of slices to send:
    Optional 'thank-you' note:
Instead of using a package with multiple classes, I put all of the code in one file.
The compiler complains if I use the keyword private or public after the first class.
How do I put multiple classes in the same file?

Thanks,

Kevin


 
Saloon Keeper
Posts: 10796
86
  • 1
  • Number of slices to send:
    Optional 'thank-you' note:
Only one class per file can be public. Doesn't matter which one. Usually the public class is the one with the main() method. The name of the public class must match the file name. Leave public and private off of the other classes. My personal preference is to put the public class first but it's not necessary.
 
kevin Abel
Ranch Foreman
Posts: 911
8
  • Number of slices to send:
    Optional 'thank-you' note:
Thank you Carey,
It worked.  The compiler errors went away.
I used Code/Reformat code from the menu in IntelliJ.  I'm not used to seeing classes without a public, private or protected at the start.  I haven't seen a lot of code example yet.  Later it will look regular to me.
The code in the book was missing a "{" .  I added it to the errata sheet.  

 
Saloon Keeper
Posts: 15619
366
  • 1
  • Number of slices to send:
    Optional 'thank-you' note:

kevin Abel wrote:I'm not used to seeing classes without a public, private or protected at the start.


That is because many people have a bad habit of making all their types public, even if the type doesn't need to be public. This bad habit also pops up in a lot of online tutorials.

If a top level type declaration or a class member doesn't have an access modifier, it has "package private" accessibility, meaning it can only be accessed by code in the same package.

Train yourself so you don't also get into the habit of making everything public by default.

  • Top level types should be package private by default. Make them public ONLY if you know you need to access them outside of the package.
  • Class members should be private by default. Give them higher accessibility ONLY if you know you need to access them outside of the current top-level type.
  • Fields should almost ALWAYS stay private. In general, the only fields that you might occasionally make more accessible are static constants.
  •  
    Marshal
    Posts: 79422
    377
    • Number of slices to send:
      Optional 'thank-you' note:

    Stephan van Hulst wrote:. . .

  • Class members should be private by default. Give them higher accessibility ONLY if you know you need to access them outside of the current top-level type.
  • . . .

    Types inside types (including classes inside classes) count as members of their enclosing types. A private member is accessible only inside its top‑level type. A protected member is accessible inside its own package and in code responsible for implementing instances of the surrounding top‑level type (I think) which includes most code in its subtypes even in different packages. That means private and protected are meaningless outside a surrounding type and top‑level classes marked with those keywords will cause fail to compile.
     
    Campbell Ritchie
    Marshal
    Posts: 79422
    377
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:. . .. . .

    I would prefer to use the name of the field unchanged. After you have gone to all the trouble of choosing a good name for the field, that code obscures it by displaying a different parameter name. I would prefer to see constructors and setXXX() methods (not that I like setXXX() methods) use the this.xxx idiom.While we're on about names, please find out why MakeHippo isn't a good name for a class.
     
    kevin Abel
    Ranch Foreman
    Posts: 911
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Stephan,
    Is package private the same thing as protected?
    Thanks,
    Kevin
     
    Saloon Keeper
    Posts: 27865
    196
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:Stephan,
    Is package private the same thing as protected?
    Thanks,
    Kevin

    No. Package private means that any class in that same package can see the property or method in question.
    The protected attribute is strictly for inheritance. It says that subclasses can access the property or method in question, regardless of what package they are in, but that no other class can see it. And that includes, if I'm not mistaken, other classes within that package that are not subclasses of the class declaring the protected property or method in question.
     
    kevin Abel
    Ranch Foreman
    Posts: 911
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Campbell,

    Campbell wrote:While we're on about names, please find out why MakeHippo isn't a good name for a class.



    My guess is that MakeHippo limits it to only making Hippos.   Animal is already used.  Maybe NewCreatureBirth could be a class name.  

    Thanks,

    Kevin  
     
    Master Rancher
    Posts: 4913
    74
    • Number of slices to send:
      Optional 'thank-you' note:
    To see the differences between the four levels of access, in one place: Java Tutorial: Access control.
     
    kevin Abel
    Ranch Foreman
    Posts: 911
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Mike,

    I looked at the link and it confused me right away when I read this:

    Controlling Access to Members of a Class
    Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control:

    At the top level—public, or package-private (no explicit modifier).
    At the member level—public, private, protected, or package-private (no explicit modifier).


    I don't know what a particular field means

    I don't understand the sentences, but the charts make sense to me.

    Thanks,

    Kevin


     
    Campbell Ritchie
    Marshal
    Posts: 79422
    377
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:. . . MakeHippo limits it to only making Hippos. . . .

    HippopotamogenicAgency would be better. But maybe HippoMaker is easier to understand
     
    Marshal
    Posts: 28262
    95
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:

    Campbell wrote:While we're on about names, please find out why MakeHippo isn't a good name for a class.



    My guess is that MakeHippo limits it to only making Hippos.   Animal is already used.  Maybe NewCreatureBirth could be a class name.    



    No. A class is a template for an object (regardless of all those beginner tutorials which only use static methods and ignore objects). And an object is a thing. An abstract thing, sure, but it's still a thing. And you use nouns to give names to things, as they teach in school. So you should be using a noun to name your class.

    You'll want to use a suitable noun, though. Your class seems to be a thing which makes a hippo, so it's a HippoMaker. It's true that NewCreatureBirth is a noun (with adjectives, but it's okay to use them too). But your class doesn't seem to be a Birth, at least not to me.
     
    Mike Simmons
    Master Rancher
    Posts: 4913
    74
    • Number of slices to send:
      Optional 'thank-you' note:
    Kevin:

    This is a class with four different fields, and four different methods.  Each particular field, that is, each individual field, has an access level that is determined by the keywords public/protected/private (or none) that are in the field's declaration.  Similarly, each particular method has an access level determined by the access keywords in its declaration.
     
    Paul Clapham
    Marshal
    Posts: 28262
    95
    • Number of slices to send:
      Optional 'thank-you' note:
    It's very confusing for beginners that "package private" access is denoted by not having any access modifier before the declaration. Usually I give the Java designers credit for knowing what they were doing, but I really don't understand making "package private" essentially the default access level. Until you get into large-scale development where you're designing classes specifically to be extended you'll get along just fine with public and private, I think.
     
    Tim Holloway
    Saloon Keeper
    Posts: 27865
    196
    • Number of slices to send:
      Optional 'thank-you' note:
    I think it's a wart. C++ had the concept of "friend", and I think that's probably what inspired package private, but yeah, if I was to pick a default, it would have been fully-private, not just package private.

    Speaking of C++. It's not uncommon to define multiple classes in a single file even if they are only loosely related. But Java mostly adheres to one class, one file, excluding inner classes.
     
    kevin Abel
    Ranch Foreman
    Posts: 911
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Mike,
    Are fields the same thing as instance variables here?  
    When I'm writing a method and declare a local variable, can I use the private, int, protected, public?   I cannot think of why I would want to do it, but I'm wondering about it.
    In your Foo class I can tell what the scope would be.  Maybe I should say from where the fields could be seen.  
    The get's are not clear to what it is demonstrating.   I notice that the private and each parameter type matches the return value of each get.  

    It's only been my second day of work and I'm having trouble concentrating on my Java hobby.  Maybe I should slow down.

     
    Carey Brown
    Saloon Keeper
    Posts: 10796
    86
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:When I'm writing a method and declare a local variable, can I use the private, int, protected, public?


    This would take 10 minutes of coding to determine and it might leave a deeper impression than just being told.
     
    Campbell Ritchie
    Marshal
    Posts: 79422
    377
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:. . . In your Foo class I can tell what the scope would be.  Maybe I should say from where the fields could be seen. . . .

    The latter. Those variables do have a scope, but scope and visibility are different.
     
    kevin Abel
    Ranch Foreman
    Posts: 911
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Carey,

    I appreciate you pointing out that I can code this to see how it works.  
    I'm not sure where to set the variables to a value.  


    }
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 15619
    366
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:When I'm writing a method and declare a local variable, can I use the private, int, protected, public?


    If your code above was meant to test whether you can apply an access modifier to a local variable, I'm not sure how it's meant to achieve that.

    You can very easily find an answer to your question using the following code:
     
    kevin Abel
    Ranch Foreman
    Posts: 911
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Stephan,

    I tried it and the compiler is complaining about all three modifiers.

    It is not what I expected.

    Kevin

     
    Stephan van Hulst
    Saloon Keeper
    Posts: 15619
    366
    • Number of slices to send:
      Optional 'thank-you' note:
    Why, what did you expect?

    Can you explain in your own words what it would mean for a local variable to be public, for instance?
     
    kevin Abel
    Ranch Foreman
    Posts: 911
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Stephan,




    The example is using the final keyword.   I think that it means that it cannot be extended or implemented.  I don't know if it serves a purpose for me in the example.

    I'm looking at the a, b and c variables as instance variables because they are before any methods in the main class.  

    I think of a local variable as being inside of a method that is inside of a class.   I cannot picture how a local variable could be public.   Maybe an instance variable could be defined as public and then the method uses it.  

    It seems to me that scopeING of variables should make more sense tome.  I'm not even sure my sentences in this post are making sense.

    Kevin
     
    Campbell Ritchie
    Marshal
    Posts: 79422
    377
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:. . . I'm looking at the a, b and c variables as instance variables . . .

    I don't like talking about a, “main class,” because it gives that class unjustified feelings of grandeur more importance than it deserves. But those variables seem to me to be inside a method. That class won't compile.

    . . . I cannot picture how a local variable could be public.

    It can't. As people told you previously, that would be meaningless.

    Maybe an instance variable could be defined as public and then the method uses it.

    Yes, but it retains its status as a field even when used inside a method.

    . . . scopeING of variables should make more sense . . .

    Scope of variables is something totally different from access. Don't confuse the two.
     
    Carey Brown
    Saloon Keeper
    Posts: 10796
    86
    • Number of slices to send:
      Optional 'thank-you' note:
    In Java, "scope" and "access" are related but distinct concepts that pertain to variables, methods, and classes:

    Scope:
    Scope refers to the region of code where a variable, method, or class is visible and can be accessed.
    It defines where in your code you can refer to a particular entity (variable, method, or class).
    Java has several levels of scope, including:
  • Block scope: Variables declared within a block of code, such as within a method or a loop, have a limited scope and are only accessible within that block.
  • Method scope: Method parameters and local variables are in scope only within the method in which they are defined.
  • Class scope: Class-level variables (static variables) and methods are accessible from anywhere within the class but may require a class instance or class name to access from outside the class.
  • Package scope: In Java, classes, methods, and variables with default (package-private) access have scope limited to the same package. They are not accessible from outside the package.
  • Public scope: Public entities are accessible from any part of the program, including other packages.

  • Access:
    Access refers to the permissions or visibility of a variable, method, or class from outside its scope.
    It defines how other parts of your code can interact with and use the entity.
    Java provides different access modifiers to control access levels:
  • Private: Entities marked as private are only accessible within the same class. They cannot be accessed from outside the class.
  • Default (package-private): Entities with default access are accessible within the same package but not from outside the package.
  • Protected: Protected entities can be accessed within the same package and by subclasses (even if they are in different packages).
  • Public: Public entities are accessible from anywhere, including different packages.

  • To summarize, scope defines where an entity can be used within your code, while access controls who can use that entity from within or outside its scope. These concepts are important for encapsulation, security, and maintaining clean and organized code in Java.
     
    kevin Abel
    Ranch Foreman
    Posts: 911
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    Campbell and Carey,

    My tutor wrote some code while explaining the attached chart to me.   I understand it a lot more now.  

    Thanks,

    Kevin
    private-public-chart.png
     
    kevin Abel
    Ranch Foreman
    Posts: 911
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    I think that the chart in my last post is for access and not scope.    

    Kevin
     
    Campbell Ritchie
    Marshal
    Posts: 79422
    377
    • Number of slices to send:
      Optional 'thank-you' note:
    Yes, that is access. It also uses the imprecise term “child”.
    The protected modifier is much more complicated than most people think
    A protected member of a class is accessible in all code resposible for implementing its instances. That does not mean in the whole of the subclass. Some subclass parts, e.g. instance methods do in fact implement the instance, and the protected members of all superclasses are accessible there. If I remember correctly, they are not however accessible in static methods, because static members of the subclass do not form part of the object's implementation. As the table shows, a protected member of a class is also accessible to all code in the same package.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 15619
    366
    • Number of slices to send:
      Optional 'thank-you' note:

    kevin Abel wrote:The example is using the final keyword.   I think that it means that it cannot be extended or implemented.  I don't know if it serves a purpose for me in the example.


    It does. It illustrates that you should make all your classes final by default. I wrote it to teach you a good habit. It isn't related to the access modifiers though.

    I'm looking at the a, b and c variables as instance variables because they are before any methods in the main class.


    Just to repeat what Campbell already pointed out, the thing in my example called "main" IS the method. So any variables declared inside of it are local variables.

    The class containing the main method is called "Example". Like Campbell, I think you should let go of the notion of a "main class", because it only seems to confuse you. There are only "main methods", no "main classes".
     
    Campbell Ritchie
    Marshal
    Posts: 79422
    377
    • Number of slices to send:
      Optional 'thank-you' note:

    Stephan van Hulst wrote:. . . it only seems to confuse you. . . .

    It seems to confuse everybody else, too
     
    Ranch Hand
    Posts: 32
    2
    • Number of slices to send:
      Optional 'thank-you' note:

    Campbell Ritchie wrote:A protected is accessible in all code resposible for implementing its instances. If I remember correctly, they are not however accessible in static methods



    It seems protected variables are accessible in static methods of subclass. This works
     
    Paul Clapham
    Marshal
    Posts: 28262
    95
    • Number of slices to send:
      Optional 'thank-you' note:
    Interesting. I always suspected that I didn't understand the access rules for protected, and now you have confirmed that.
     
    Mike Simmons
    Master Rancher
    Posts: 4913
    74
    • Number of slices to send:
      Optional 'thank-you' note:
    I'm not sure where the idea that protected methods aren't accessible from static methods might have come from.  When talking about static methods, we often need to include a caveat that you can't access their instance methods or instance fields without an instance.  For a static method, that typically needs to be an instance passed into the method as an argument, because there's no "this" instance.  But, that's true for public methods too. There's no notion that accessibility is about protecting an instance - it's about protecting all the implementation for a particular class.
     
    kevin Abel
    Ranch Foreman
    Posts: 911
    8
    • Number of slices to send:
      Optional 'thank-you' note:
    This was a lot of stuff to learn.

    I'll remember that main is a method.  That's enough for me now.

    Kevin
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 15619
    366
    • Number of slices to send:
      Optional 'thank-you' note:
    You don't need to remember it. You can deduce it from the syntax.

    A type declaration contains one of the following keywords: class, enum, record, interface.

    The declaration for main doesn't contain any of those keywords, so it must be a field, a constructor or a method.

    It can't be a field, because it has an argument list and a body. It can't be a constructor, because it has a return type. Therefore, it must be a method.
     
    Campbell Ritchie
    Marshal
    Posts: 79422
    377
    • Number of slices to send:
      Optional 'thank-you' note:

    Stephan van Hulst wrote:. . . It can't be a constructor, because it has a return type. . . . .

    . . . and its name is different from the class'. But beware: the following code, if completed, will compile and run and cause nasty errors because you think you have written a constructor and you have actually written a method:-
     
    Tim Holloway
    Saloon Keeper
    Posts: 27865
    196
    • Number of slices to send:
      Optional 'thank-you' note:
    The "main" method is not magic. It's an ordinary method just like any other.

    However, the JVM has been designed so that the point where execution of Java begins has to be a method in a class. To make it easier to locate that starting point, the JVM looks for a particular method signature. Specifically, a method declared static, scope public, returning void, and having one argument, which is an array of java.lang.String. When it finds it in the class named on the command like (or for "-jar" execution, in the JAR manifest), then the JVM invokes that method and the show begins.

    You can define another method with a signature of "public void main()" with no arguments and that is syntactically legal. But the JVM won't use it as a starting method. Not even if you declare it static. For that matter a non-static "public void main(String [])" won't work eiither. Not  only does the signature fail to match, but also at that point there is no object to invoke that method on!
     
    Carey Brown
    Saloon Keeper
    Posts: 10796
    86
    • Number of slices to send:
      Optional 'thank-you' note:
    Interestingly  enough, this works
    because variable length args are turned into an array before calling the method.
     
    Don't get me started about those stupid light bulbs.
    reply
      Bookmark Topic Watch Topic
    • New Topic
    vceplus-200-125    | boson-200-125    | training-cissp    | actualtests-cissp    | techexams-cissp    | gratisexams-300-075    | pearsonitcertification-210-260    | examsboost-210-260    | examsforall-210-260    | dumps4free-210-260    | reddit-210-260    | cisexams-352-001    | itexamfox-352-001    | passguaranteed-352-001    | passeasily-352-001    | freeccnastudyguide-200-120    | gocertify-200-120    | passcerty-200-120    | certifyguide-70-980    | dumpscollection-70-980    | examcollection-70-534    | cbtnuggets-210-065    | examfiles-400-051    | passitdump-400-051    | pearsonitcertification-70-462    | anderseide-70-347    | thomas-70-533    | research-1V0-605    | topix-102-400    | certdepot-EX200    | pearsonit-640-916    | itproguru-70-533    | reddit-100-105    | channel9-70-346    | anderseide-70-346    | theiia-IIA-CIA-PART3    | certificationHP-hp0-s41    | pearsonitcertification-640-916    | anderMicrosoft-70-534    | cathMicrosoft-70-462    | examcollection-cca-500    | techexams-gcih    | mslearn-70-346    | measureup-70-486    | pass4sure-hp0-s41    | iiba-640-916    | itsecurity-sscp    | cbtnuggets-300-320    | blogged-70-486    | pass4sure-IIA-CIA-PART1    | cbtnuggets-100-101    | developerhandbook-70-486    | lpicisco-101    | mylearn-1V0-605    | tomsitpro-cism    | gnosis-101    | channel9Mic-70-534    | ipass-IIA-CIA-PART1    | forcerts-70-417    | tests-sy0-401    | ipasstheciaexam-IIA-CIA-PART3    | mostcisco-300-135    | buildazure-70-533    | cloudera-cca-500    | pdf4cert-2v0-621    | f5cisco-101    | gocertify-1z0-062    | quora-640-916    | micrcosoft-70-480    | brain2pass-70-417    | examcompass-sy0-401    | global-EX200    | iassc-ICGB    | vceplus-300-115    | quizlet-810-403    | cbtnuggets-70-697    | educationOracle-1Z0-434    | channel9-70-534    | officialcerts-400-051    | examsboost-IIA-CIA-PART1    | networktut-300-135    | teststarter-300-206    | pluralsight-70-486    | coding-70-486    | freeccna-100-101    | digitaltut-300-101    | iiba-CBAP    | virtuallymikebrown-640-916    | isaca-cism    | whizlabs-pmp    | techexams-70-980    | ciscopress-300-115    | techtarget-cism    | pearsonitcertification-300-070    | testking-2v0-621    | isacaNew-cism    | simplilearn-pmi-rmp    | simplilearn-pmp    | educationOracle-1z0-809    | education-1z0-809    | teachertube-1Z0-434    | villanovau-CBAP    | quora-300-206    | certifyguide-300-208    | cbtnuggets-100-105    | flydumps-70-417    | gratisexams-1V0-605    | ituonline-1z0-062    | techexams-cas-002    | simplilearn-70-534    | pluralsight-70-697    | theiia-IIA-CIA-PART1    | itexamtips-400-051    | pearsonitcertification-EX200    | pluralsight-70-480    | learn-hp0-s42    | giac-gpen    | mindhub-102-400    | coursesmsu-CBAP    | examsforall-2v0-621    | developerhandbook-70-487    | root-EX200    | coderanch-1z0-809    | getfreedumps-1z0-062    | comptia-cas-002    | quora-1z0-809    | boson-300-135    | killtest-2v0-621    | learncia-IIA-CIA-PART3    | computer-gcih    | universitycloudera-cca-500    | itexamrun-70-410    | certificationHPv2-hp0-s41    | certskills-100-105    | skipitnow-70-417    | gocertify-sy0-401    | prep4sure-70-417    | simplilearn-cisa    |
    http://www.pmsas.pr.gov.br/wp-content/    | http://www.pmsas.pr.gov.br/wp-content/    |