Can a java file have more than one class?
Asked Answered
G

18

124

What is the purpose of having more than one class in a Java file ? I am new to Java.

Edited: That can be achieved by creating a inner class inside a public class, right?

Galanti answered 9/6, 2009 at 5:43 Comment(1)
Possible duplicate of In java can i have more than one class/object in a file?Andriette
B
147

Yes, it can. However, there can only be one public top-level class per .java file, and public top-level classes must have the same name as the source file.

The purpose of including multiple classes in one source file is to bundle related support functionality (internal data structures, support classes, etc) together with the main public class. Note that it is always OK not to do this--the only effect is on the readability (or not) of your code.

Brassica answered 9/6, 2009 at 5:47 Comment(6)
I think it's a good idea to do so if you want to keep that extra classes private, so they can be completely changed later without breaking anything outside that accidentally uses those classes.Esquimau
It's in there for 1.0 compatibility (before nested classes). It is a big mistake in the language. The biggest advantage for using it is that IDEs have hopeless file handling.Tarkany
One public, top-level class per file. There can be as many public inner classes per file as you like.Maracaibo
@Tom, which part do you think is a mistake, inner classes or multiple top-level classes per file?Notarize
@Notarize Multiple top-level classes per file. It's just so wrong. Where is java.awt.LightweightDispatcher?Tarkany
@Tom, I found it by typing the name in Eclipse then pressing F3 :-) I assume this is second nature to C# programmers. C# allows multiple classes per file too, but with no restrictions on their visibility.Notarize
P
20

If you want to implement a public class, you must implement it in a file with the same name as that class. A single file can contain one public and optionally some private classes. This is useful if the classes are only used internally by the public class. Additionally the public class can also contain inner classes.

Although it is fine to have one or more private classes in a single source file, I would say that is more readable to use inner and anonymous classes instead. For example one can use an anonymous class to define a Comparator class inside a public class:

  public static Comparator MyComparator = new Comparator() {
    public int compare(Object obj, Object anotherObj) {

    }
  };

The Comparator class will normally require a separate file in order to be public. This way it is bundled with the class that uses it.

Pregnable answered 9/6, 2009 at 5:48 Comment(1)
It's not really a private class if it's in the file with no-modifier . You can't have a private class without it being an inner class because if you did, who could use it?Chesson
P
10

Yes, as many as you want!

BUT, only one "public" class in every file.

Plumule answered 9/6, 2009 at 6:53 Comment(0)
A
8

A .java file is called a compilation unit. Each compilation unit may contain any number of top-level classes and interfaces. If there are no public top-level types then the compilation unit can be named anything.

//Multiple.java
//preceding package and import statements

class MyClass{...}
interface Service{...}
...
//No public classes or interfaces
...

There can be only one public class/interface in a compilation unit. The c.u. must be named exactly as this public top-level type.

//Test.java
//named exactly as the public class Test
public class Test{...}
//!public class Operations{...}
interface Selector{...}
...
//Other non-public classes/interfaces

Important points about the main method - part 1

Part 2

(Points regarding the number of classes and their access levels covered in part 2)

Atheroma answered 10/5, 2014 at 11:59 Comment(0)
R
6

In general, there should be one class per file. If you organise things that way, then when you search for a class, you know you only need to search for the file with that name.

The exception is when a class is best implemented using one or more small helper classes. Usually, the code is easiest to follow when those classes are present in the same file. For instance, you might need a small 'tuple' wrapper class to pass some data between method calls. Another example are 'task' classes implementing Runnable or Callable. They may be so small that they are best combined with the parent class creating and calling them.

Rodomontade answered 9/6, 2009 at 5:52 Comment(0)
P
6

Yes you can have more than one class inside a .java file. At most one of them can be public. The others are package-private. They CANNOT be private or protected. If one is public, the file must have the name of that class. Otherwise ANYTHING can be given to that file as its name.

Having many classes inside one file means those classes are in the same package. So any other classes which are inside that package but not in that file can also use those classes. Moreover, when that package is imported, importing class can use them as well.

For a more detailed investigation, you can visit my blog post in here.

Pentachlorophenol answered 5/3, 2017 at 4:18 Comment(1)
Welcome to Stack Overflow! I appreciate that you expounded on information that wasn't already covered here. You also did a good job of citing your blog post while declaring ownership and including relevant information here. If you choose to contribute more to this site in the future (and I hope you do), make sure to consider this article to make sure your posts continue to be well received if you cite your blog.Barbirolli
C
5

Yes you can create more than one public class, but it has to be a nested class.

public class first {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }

    public class demo1
    {

        public class demo2
        {

        }
    }
}
Corettacorette answered 2/5, 2017 at 4:19 Comment(0)
M
4

Besides anonymous inner classes, another use is private inner classes that implement a public interface (see this article). The outer class can access all private fields and methods of the inner class.

This lets you create two tightly-coupled classes, such as a model and its view, without exposing the implementations of either. Another example is a collection and its iterators.

Megen answered 9/6, 2009 at 5:53 Comment(0)
C
4

Yes 200%,

Example:

class A {
 void methodDeclaration() { System.out.println("!!!"); }
 }
 class B {
 public static void main(String[] args) {
new A().methodDeclaration();
    }
 }
Concubinage answered 5/3, 2017 at 4:24 Comment(0)
T
2

Yes it can,but there can only be 1 public class inside any package as java compiler creates the .Class file which is of the same name as the Public class name therefore if their are more than 1 public class it would be difficult to select for compiler that what should be the name of Class file.

Turnbow answered 9/6, 2009 at 5:48 Comment(0)
A
2

Yes ! .java file can contain only one public class.

If you want these two classes to be public they have to be put into two .java files: A.java and B.java.

Aphorize answered 3/1, 2017 at 15:40 Comment(1)
I'm not sure than your response add anything more from the 12 others answersSiegfried
C
2

Yes, it can. However, there can only be one public class per .java file, as public classes must have the same name as the source file.

Clint answered 13/10, 2019 at 19:19 Comment(0)
M
1

Varies... One such example would be an anonymous classes (you'll encounter those alot when using event listeners and such).

Machismo answered 9/6, 2009 at 5:46 Comment(0)
L
1

I think it should be "there can only be one NON-STATIC top level public class per .java file". Isn't it?

Loy answered 16/10, 2012 at 2:41 Comment(1)
You should ask this as a question rather than answering here.Velours
F
1

If you want to implement a singleton, that is a class that runs in your program with only one instance in memory throughout the execution of the application, then one of the ways to implement a singleton is to nest a private static class inside a public class. Then the inner private class only instantiates itself when its public method to access the private instance is called.

Check out this wiki article,

https://en.wikipedia.org/wiki/Singleton_pattern

The concept takes a while to chew on.

Fletcher answered 26/12, 2015 at 20:9 Comment(0)
S
1

In a .java file,there can be only one public top-level class whose name is the same as the file, but there might be several public inner classes which can be exported to everyone and access the outer class's fields/methods,for example:AlertDialog.Builder(modified by 'public static') in AlertDialog(modified by 'public')

Steamroller answered 15/8, 2016 at 9:25 Comment(0)
W
1

Yes You can have more than one Class in one .Java file . But You have make one of them Public . and save .java file with same name as name of public class. when you will compile that .java file than you will get Separate .class files for each class defined in .java file .

Apart from this there are too many method for defining more than one class in one .java file .

  1. use concept of Inner Classes.
  2. Use Concept of Anonymous Classes .
Wholewheat answered 29/12, 2016 at 9:14 Comment(0)
M
0

There can only be one public class top level class in a file. The class name of that public class should be the name of the file. It can have many public inner classes.

You can have many classes in a single file. The limits for various levels of class visibility in a file are as follows:

Top level classes:
1 public class
0 private class
any number of default classes

Inner classes:
any number of inner classes with any visibility (default, private, protected, public)

Please correct me if I am wrong.

Monasticism answered 16/10, 2017 at 7:30 Comment(1)
Can't have a protected top level class - see here for the reason why.Veal

© 2022 - 2024 — McMap. All rights reserved.