Can a java file have more than one class?

JavaClass

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

Yes, as many as you want!

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

Solution 4 - Java

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)

Solution 5 - Java

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.

Solution 6 - Java

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.

Solution 7 - Java

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
		{
			
		}
	}
}

Solution 8 - Java

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.

Solution 9 - Java

Yes 200%,

Example:

class A {
 void methodDeclaration() { System.out.println("!!!"); }
 }
 class B {
 public static void main(String[] args) {
new A().methodDeclaration();
    }
 }

Solution 10 - Java

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.

Solution 11 - Java

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.

Solution 12 - Java

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.

Solution 13 - Java

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

Solution 14 - Java

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

Solution 15 - Java

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.

Solution 16 - Java

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')

Solution 17 - Java

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 .

Solution 18 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyesraajView Question on Stackoverflow
Solution 1 - JavaSean ReillyView Answer on Stackoverflow
Solution 2 - JavakgiannakakisView Answer on Stackoverflow
Solution 3 - JavaAlbertoView Answer on Stackoverflow
Solution 4 - JavaUtsavView Answer on Stackoverflow
Solution 5 - JavaConfusionView Answer on Stackoverflow
Solution 6 - JavaMerter SualpView Answer on Stackoverflow
Solution 7 - JavaGaneshView Answer on Stackoverflow
Solution 8 - JavaRich ApodacaView Answer on Stackoverflow
Solution 9 - JavaShivanandamView Answer on Stackoverflow
Solution 10 - JavaMeetu ChoudharyView Answer on Stackoverflow
Solution 11 - JavaRakesh SinghView Answer on Stackoverflow
Solution 12 - Javauser3077069View Answer on Stackoverflow
Solution 13 - JavalaginimainebView Answer on Stackoverflow
Solution 14 - JavaHolidayCactusView Answer on Stackoverflow
Solution 15 - JavachrismjhView Answer on Stackoverflow
Solution 16 - JavaBaoyangView Answer on Stackoverflow
Solution 17 - JavaGaurav VarshneyView Answer on Stackoverflow
Solution 18 - JavaLakshmikant DeshpandeView Answer on Stackoverflow