Other Class-Related Concepts

Packages

A package is a loose affiliation of classes. Classes that are in the same package can access other classes and members in the package, whether you declare them public or not.

Defining a package

The first line of a Java source code file can include the keyword package, followed by the package name. Classes contained within a source file that don't include the keyword package are put into the default package.

Accessing the members of a package

Classes that are members of the same package as the current class are automatically accessible to the current class.

The current class can access classes contained in other packages. To do so, the current class specifies the entire class name, including the package name, as in the following example:

class TV
{
 com.ms.wfc.ui.Button button = new com.ms.wfc.ui.Button();
}


A class in another package can be made directly accessible by importing it using the import keyword:

import com.ms.wfc.ui.Button;
class TV
{
 Button button = new Button();
}


All of the classes of a given package can be imported at the same time using a wildcard character, as follows:

import com.ms.wfc.ui.*;
class TV
{
 Button button = new Button();
}


It's not possible to import all of the subpackages of a package using the wildcard character. Thus, import com.ms.wfc.* doesn't import the com.ms.wfc.ui package. In addition, no other wildcard character than * is allowed.

Default packages

Since the packages java.lang and java.util are critical to the operation of any Java program, Java automatically imports these packages.

Object Class

Object is the base class of all classes. If you don't specify a base class, your class extends Object directly. Thus, the following two class definitions are completely equivalent:

class MyClass1 // extends Object by default
{
}
class MyClass2 extends Object
{
}


A method can pass any object to a method that accepts an instance of class Object as its argument.

String Class

The class String represents Unicode character strings. The String class offers a series of useful methods, such as concat() to concatenate two strings, compareTo() to compare two strings, toUpperCase() to convert the string to all uppercase characters, and toLowerCase() to convert the string to all lowercase characters. The following two properties—double quotes and +—are reserved to the class String.

You can create an object of class String by encompassing a string of characters within double quotes. Thus, the two following declarations are equivalent:

String s1 = "This is a string";
String s2 = new String("This is a string");


In addition, the + operator is extended to the String class to perform conversion (if necessary) and concatenation:

int count = 1;
String s = "This is the number " + count + " string in the list";


Comments