Tuesday, July 28, 2015

scjp summary


Before we dig into class declarations, let's do a quick review of the rules associated with declaring classes,
  There can be only one public class per source code file.
Comments can appear at the beginning or end of any line in the source code file; they are independent of any of the positioning rules discussed here.
If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Dog { } must be in a source code file named Dog.java.
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.
the first line in the source code file.
If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn't a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements, the class declaration must be
import and package statements apply to all classes within a source code file. In other words, there's no way to declare multiple classes in a file and have them in different packages, or use different imports.

Class Declarations and Modifiers
Java is a package-centric language; the developers assumed that for good organization and name scoping, you would put all your classes into packages.
They were right, and you should. Imagine this nightmare: Three different programmers, in the same company but working on different parts of a project, write a class named Utilities. If those three Utilities classes have not been declared in any explicit package, and are in the classpath, you won't have any way to tell the compiler or JVM which of the three you're trying to reference. Sun recommends that developers use reverse domain names, appended with division and/or project names. For example, if your domain name is geeksanonymous.com, and you're working on the client code for the TwelvePointOSteps program, you would name your package something like com.geeksanonymous.steps.client. That would essentially change the name of your class to com.geeksanonymous.steps.client.Utilities. You might still have name collisions within your company, if you don't come up with your own naming schemes, but you're guaranteed not to collide with
classes developed outside your company (assuming they follow Sun's naming  convention, and if they don't, well, Really Bad Things could happen).
A file can have more than one nonpublic class.Files with no public classes can have a name that does not match any of the classes in the file.

import statements, and package statements in a source file:

Source File Declaration Rules

No comments:

Post a Comment

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...