. . .

What are the source file declaration rules in java?

About to declare classes……

When you write code in Java, you’re writing classes or interfaces. Within those classes, as you know, are variables and methods (plus a few other things). How you declare your classes, methods, and variables dramatically affects your code’s behavior. For example, a public method can be accessed from code running anywhere in your application. Mark that method private, though, and it vanishes from everyone’s radar (except the class in which it was declared). For this objective, we’ll study the ways in which you can declare and modify (or not) a class. You’ll find that we cover modifiers in an extreme level of detail, and though we know you’re already familiar with them, we’re starting from the very beginning.

Before we dig into class declarations, let’s do a quick review of the rules associated with declaring classes, import statements, and package statements in a source file:

  1. There can be only one public class per source code file.
  2. Comments can appear at the beginning or end of any line in the source code file.
  3. If there is a public class in a file, the name of the file must match the name of the public class.
  4. If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present.
  5. If there are import statements, they must go between the package statement (if there is one) and the class declaration.
  6. If there isn’t a package statement, then the import statement(s) must be the first line(s) in the source code file.
  7. If there are no package or import statements, the class declaration must be in the first line in the source code file.
  8. import and package statements apply to all classes within a source code file.
  9. In other words, there’s no way to declare multiple classes in a file and have them in different packages or use different imports.
Please share the article

Leave a Reply

Your email address will not be published. Required fields are marked *

two × 5 =