• 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: 914
10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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: 10804
86
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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: 914
10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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: 15630
366
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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: 79471
    379
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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: 79471
    379
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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: 914
    10
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Stephan,
    Is package private the same thing as protected?
    Thanks,
    Kevin
     
    Saloon Keeper
    Posts: 27884
    198
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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: 914
    10
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 4921
    74
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    To see the differences between the four levels of access, in one place: Java Tutorial: Access control.
     
    kevin Abel
    Ranch Foreman
    Posts: 914
    10
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 79471
    379
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

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

    HippopotamogenicAgency would be better. But maybe HippoMaker is easier to understand
     
    Marshal
    Posts: 28263
    95
    Eclipse IDE Firefox Browser MySQL Database
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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: 4921
    74
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 28263
    95
    Eclipse IDE Firefox Browser MySQL Database
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 27884
    198
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 914
    10
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 10804
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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: 79471
    379
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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: 914
    10
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 15630
    366
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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: 914
    10
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 15630
    366
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 914
    10
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 79471
    379
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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: 10804
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 914
    10
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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
    [Thumbnail for private-public-chart.png]
     
    kevin Abel
    Ranch Foreman
    Posts: 914
    10
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I think that the chart in my last post is for access and not scope.    

    Kevin
     
    Campbell Ritchie
    Marshal
    Posts: 79471
    379
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 15630
    366
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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: 79471
    379
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

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

    It seems to confuse everybody else, too
     
    Ranch Hand
    Posts: 32
    2
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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: 28263
    95
    Eclipse IDE Firefox Browser MySQL Database
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 4921
    74
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 914
    10
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 15630
    366
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 79471
    379
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    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: 27884
    198
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    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: 10804
    86
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Interestingly  enough, this works
    because variable length args are turned into an array before calling the method.
     
    If you look closely at this tiny ad, you will see five bicycles and a naked woman:
    a bit of art, as a gift, that will fit in a stocking
    https://gardener-gift.com
    reply
      Bookmark Topic Watch Topic
    • New Topic