Java in detail: referring to classes in a different package, import statements , and the class java.lang July 25, 2008
Posted by crystalchangdin in education and career in Sweden.trackback
referring to classes in a different package
To reference a class defined in another package we must use a fully qualified class name. That is, we prefix the package name to the class name, as
PackageName.ClassName
The fully qualified name of the class B1 in package B is B.B1; the fully qualified name od the class LineBorder in the package javax.swing.border is
javax.swing.border.LineBorder
The definition of a variable of type B1 in class A2 which is in package A would look something like this
private B.B1 myB1;
and an initialization statement like this:
myB1 = new B.B1();
The import statement
By using an import statement, we can refer to a class in another package with its simple name rather than with its fully qualified name. Import statements are placed at the beginning of a compilation unit(file), after the package statement, and apply to all classes defined in the compilation unit.
For example,
import javax.swing.border.LineBorder;
import javax.swing.border.*;
The first statement allows the simple name of the specified class to be written in the compilation unit in place of the fully qualified name. We can write
LineBorder myBorder;
and
myBorder = new LineBorder(myColor);
rather than
javax.swing.border.LineBorder myBorder;
and
myBorder = new javax.swing.border.LineBorder(myColor);
The package java.lang
The predefined package java.lang contains the definitions of a number of commonly used classes, such as String. Since use of these classes is so commonplace, Java allows them to be referenced by their simple names without an import statement. That is, you can imagine that every compilation unit implicitly contains the statement
import java.lang.*;
immediately after the package statement.
Comments»
No comments yet — be the first.