1

I'm learning about Java and have just encountered 2 instructions:

  1. A class must have a matching filename
  2. Remember that the name of the java file should match the class name

Ask:

Should in (2) LIKE or DIFFERENT Must in (1) ?? -> (1), (2).

What is correct ??

alepuzio
  • 1,350
  • 2
  • 28
  • 36
Puskin
  • 94
  • 1
  • 8
  • 5
    This isn't a technical question. By convention the java filename matches the classname and it helps in identifying which class lives where. Also if this is a homework problem, this will get you no where. – Mike Tung Dec 20 '18 at 13:46
  • I just want it is Obligatory or not – Puskin Dec 20 '18 at 13:49
  • Try it... Try to create a class `Node` and store it in a file named `Note.java`, then try to compile it. – deHaar Dec 20 '18 at 13:50
  • This site's purpose is to help with objective questions in programming. Read [How to ask questions](https://stackoverflow.com/help/mcve) – Mike Tung Dec 20 '18 at 13:51
  • Then try `public` vs non-`public` classes that match and don't match the filename. – Dave Newton Dec 20 '18 at 13:51
  • 2
    Then recognize that just because some *compilers* have rules about this, there's no reason other than convention for those compilers' rules. Mentioned briefly in the JLS: https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.6 – Dave Newton Dec 20 '18 at 13:59
  • thank you everyone for the advice – Puskin Dec 20 '18 at 17:27

2 Answers2

2

As mentioned in the comments, this is not as clear as it might seem at first, partly because the JLS does not require packages to be stored in a file system:

7.6. Top Level Type Declarations :

If and only if packages are stored in a file system (§7.2), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:
[...]

So your answer is basically:

It may be a "must", depending on your compiler.

Hulk
  • 5,295
  • 1
  • 25
  • 49
2

To be fully precise:

  • A public class X must sit in X.java (see the nice answer by user Hulk for this "must")
  • Beyond that, non-public classes Y, Z should live in Y.java and Z.java, but they can also go into X.java

The Google coding standard for example emphasizes that second rule. You are supposed to have one top level class per file, and then the class name should match the file name.

Doing anything else is most likely going to confuse any experienced Java programmer. And confusing your readers is always a bad idea.

GhostCat
  • 127,190
  • 21
  • 146
  • 218