Java public class in one file

Класс Х публичный и должен быть объявлен в файле с именем Х

Здравствуйте.
С самой ошибкой я разобрался. Убрал public, оставил его только для GameLauncher и всё скомпилилось и завелось.
Вопрос в другом.
Какой класс правильно объявить публичным?
И почему в книге пример с ошибками (код был из книги)? Возможно связано с тем что книга по java 5.
Буду очень благодарен, если объясните по какому принципу объявлять класс публичным и почему так вышло с примеров книги.

Моя версия JSE
java version «13.0.1» 2019-10-15
Java(TM) SE Runtime Environment (build 13.0.1+9)
Java HotSpot(TM) 64-Bit Server VM (build 13.0.1+9, mixed mode, sharing)

Ошибка при компиляции. Использую javac без каких либо IDE.
GameLauncher.java:1: error: class GuessGame is public, should be declared in a file named GuessGame.java
public class GuessGame ^
GameLauncher.java:61: error: class Player is public, should be declared in a file named Player.java
public class Player ^
2 errors

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
public class GuessGame { Player p1; Player p2; Player p3; public void startGame() { p1 = new Player(); p2 = new Player(); p3 = new Player(); int guessp1 = 0; int guessp2 = 0; int guessp3 = 0; boolean p1isRight = false; boolean p2isRight = false; boolean p3isRight = false; int targetNumber = (int) (Math.random() * 10); System.out.println("Я загадываю число от 0 до 9. "); while(true) { p1.guess(); p2.guess(); p3.guess(); guessp1 = p1.number; System.out.println("Первый игрок думает что это " + guessp1); guessp2 = p2.number; System.out.println("Второй игрок думает что это " + guessp2); guessp3 = p3.number; System.out.println("Третий игрок думает что это " + guessp3); if (guessp1 == targetNumber) { p1isRight = true; } if (guessp2 == targetNumber) { p2isRight = true; } if (guessp3 == targetNumber) { p3isRight = true; } if (p1isRight || p2isRight || p3isRight) { System.out.println("У нас есть победитель!"); System.out.println("Первый игрок угадал? " + p1isRight); System.out.println("Второй игрок угадал? " + p2isRight); System.out.println("Третий игрок угадал? " + p3isRight); System.out.println("Конец игры"); break; } else { System.out.println("Игроки должны попробовать ещё раз."); } } } } public class Player { int number = 0; public void guess() { number = (int)(Math.random() * 10); System.out.println("Думаю что это число " + number); } } public class GameLauncher { public static void main(String[] args) { GuessGame game = new GuessGame(); game.startGame(); } }

Источник

Why a Single Java Source File Can Not Have More Than One Public Class

Join the DZone community and get the full member experience.

According to Java standards and common practices, we should declare every class in its own source file. And even if we declare multiple classes in a single source file (.java), still each class will have its own class file after compilation. But the fact is that we can declare more than one class in a single source file with these constraints,

  • Each source file should contain only one public class and the name of that public class should be similar to the name of the source file.
  • If you are declaring a main method in your source file then main should lie in that public class.

If there is no public class in the source file then main method can lie in any class and we can give any name to the source file.

If you are not following the first constraint then you will receive a compilation error saying “The public type A must be defined in its own file”. While if you are not following the second constraint you will receive an error “Error: Could not find or load main class User” after execution of the program, and if you try this in Eclipse, then you will not get the option to execute the program.

Читайте также:  Tostring in class java lang object

Why Only One Public Class Per Source File

Now we know that we can’t declare more than one public file in a single source file. Now we will look at why we can’t do this or why it is not allowed in Java.

Well, actually it is an optional restriction according to Java Language Specification (Section 7.6, Page No. 209), but it is followed by the Oracle Java compiler as a mandatory restriction. According to Java Language Specification:

  • The type is referred to by code in other compilation units of the package in which the type is declared.
  • The type is declared public (and therefore is potentially accessible from code in other packages).

For example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket , and the corresponding object code would be found in the file Toad.class in the same directory.

The above clarification is little bit difficult to understand, So let’s replace the “type” word with actual a class Toad to get more clarification:

  • Toad class is referred in other classes in same package.
  • Toad class is declared public.

To get a more clear picture, let’s imagine there are two public classes—public class A and public class B—in the same source file, and class A has reference to the not-yet-compiled class B. And we are compiling (compiling-linking-loading) class A now while linking to class B—the compiler will be forced to examine each *.java files within the current package because class B doesn’t have it’s specific B.java file. So, in the above case, it is a little bit time consuming for the compiler to find which class lies under which source file and in which class the main method lies.

So the reason behind keeping one public class per source file is to actually make the compilation process faster because it enables a more efficient lookup of source and compiled files during linking (import statements). The idea is if you know the name of a class, you know where it should be found for each classpath entry and no indexing will be required.

And also as soon as we execute our application, JVM by default looks for the public class (since there are no restrictions and it can be accessible from anywhere), and it also looks for public static void main(String args[]) in that public class. The public class acts as the initial class from where the JVM instance for the Java application (program) is begun. So when we provide more than one public class in a program the compiler itself stops you by throwing an error. This is because later we can’t confuse the JVM as to which class is to be its initial class, because only one public class with the public static void main(String args[]) is the initial class for JVM.

Читайте также:  Python os system example

But why can we declare more than one non-public class (default access) in a single source file?

Although there is no particular specification or reference to point out why it is allowed to have more than one non-public class per source file, presumably the point is that developers are more likely to want to find the source code for a public class than a non-public one, since developers don’t work on the same package provided by others, so they don’t need to know the non-public classes. So the compiler should not worry too much about linking a non-public class because these are private to the package.

But we should always declare every class in its own file because it we will make the source short, simple, well organised and easy to understand.

Published at DZone with permission of Naresh Joshi , DZone MVB . See the original article here.

Opinions expressed by DZone contributors are their own.

Источник

Why a Single Java Source File Can Not Have More Than One Public Class

Join the DZone community and get the full member experience.

According to Java standards and common practices, we should declare every class in its own source file. And even if we declare multiple classes in a single source file (.java), still each class will have its own class file after compilation. But the fact is that we can declare more than one class in a single source file with these constraints,

  • Each source file should contain only one public class and the name of that public class should be similar to the name of the source file.
  • If you are declaring a main method in your source file then main should lie in that public class.

If there is no public class in the source file then main method can lie in any class and we can give any name to the source file.

If you are not following the first constraint then you will receive a compilation error saying “The public type A must be defined in its own file”. While if you are not following the second constraint you will receive an error “Error: Could not find or load main class User” after execution of the program, and if you try this in Eclipse, then you will not get the option to execute the program.

Why Only One Public Class Per Source File

Now we know that we can’t declare more than one public file in a single source file. Now we will look at why we can’t do this or why it is not allowed in Java.

Well, actually it is an optional restriction according to Java Language Specification (Section 7.6, Page No. 209), but it is followed by the Oracle Java compiler as a mandatory restriction. According to Java Language Specification:

  • The type is referred to by code in other compilation units of the package in which the type is declared.
  • The type is declared public (and therefore is potentially accessible from code in other packages).
Читайте также:  Модули в python что такое

For example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket , and the corresponding object code would be found in the file Toad.class in the same directory.

The above clarification is little bit difficult to understand, So let’s replace the “type” word with actual a class Toad to get more clarification:

  • Toad class is referred in other classes in same package.
  • Toad class is declared public.

To get a more clear picture, let’s imagine there are two public classes—public class A and public class B—in the same source file, and class A has reference to the not-yet-compiled class B. And we are compiling (compiling-linking-loading) class A now while linking to class B—the compiler will be forced to examine each *.java files within the current package because class B doesn’t have it’s specific B.java file. So, in the above case, it is a little bit time consuming for the compiler to find which class lies under which source file and in which class the main method lies.

So the reason behind keeping one public class per source file is to actually make the compilation process faster because it enables a more efficient lookup of source and compiled files during linking (import statements). The idea is if you know the name of a class, you know where it should be found for each classpath entry and no indexing will be required.

And also as soon as we execute our application, JVM by default looks for the public class (since there are no restrictions and it can be accessible from anywhere), and it also looks for public static void main(String args[]) in that public class. The public class acts as the initial class from where the JVM instance for the Java application (program) is begun. So when we provide more than one public class in a program the compiler itself stops you by throwing an error. This is because later we can’t confuse the JVM as to which class is to be its initial class, because only one public class with the public static void main(String args[]) is the initial class for JVM.

But why can we declare more than one non-public class (default access) in a single source file?

Although there is no particular specification or reference to point out why it is allowed to have more than one non-public class per source file, presumably the point is that developers are more likely to want to find the source code for a public class than a non-public one, since developers don’t work on the same package provided by others, so they don’t need to know the non-public classes. So the compiler should not worry too much about linking a non-public class because these are private to the package.

But we should always declare every class in its own file because it we will make the source short, simple, well organised and easy to understand.

Published at DZone with permission of Naresh Joshi , DZone MVB . See the original article here.

Opinions expressed by DZone contributors are their own.

Источник

Оцените статью