Learnitweb

Rules of declaring package, import and class in source file

While writing source code, following are the rules of declaring package, import statement and class:

  • There can be only one public class per source code file. It means, in one .java file, there can not be two or more public class file. There should only be one public class in a source code file.
  • You can declare multiple non public class in a single source code file.
  • If there is a public class in a source code file, then the name of the file should be same as class name. For example:
public class Foo {
	//your code
}

This class should be saved as Foo.java as the the source code has class which is public.

  • Comments can appear at the beginning or the end of file.
  • If the class is a part of package, then package statement should be the first statement of the file. package statement should come before any import statement.
  • import statement should come after package statement and before class declaration. If there is no package statement then import statement should be the first statement in the source code.
  • If there are multiple non public classes in a source code file, the source code file can be saved as a different name that does not match with any of the class in the file.