Java Reference
In-Depth Information
Example 3.6 Using simple class
// declare a reference to one:
PairInt twovals;
// now create one:
twovals = new PairInt(5, 4);
// we can also declare and create in one step:
PairInt twothers = new PairInt(7, 11);
time to run the program, its various classes are loaded as needed. We'll discuss
grouping classes together and how Java locates them in Section 3.3.1.
In Java, each source file contains one class and the file is named after that
class. It is possible to define inner classes located inside another class definition
and thus inside its file, but that introduces other complexities that we wish to
avoid discussing at this point. Most importantly, an inner class has access to
even the private members of the enclosing class. (Read more about inner classes
in any of the Java topic that we recommend at the end of this chapter.)
For each of the class methods, class data declarations, and the class itself,
Java has syntax to limit the scope , or visibility, of those pieces. The examples
above didn't include those keywords—that is, they took the default values.
Usually you'll want to specify something. See Section 3.4.1.
3.2.2.1
So far we have not explained something important about object type variables.
These variables can all be thought of as pointers or references to an object.
When you declare a variable of an object type, what you are declaring is a vari-
able that is capable of referring to an object of that type. When declared, it does
not point at anything. It has a value of null and any attempt to use it will result
in a null pointer exception (more on those later).
Before an object variable might be used, it must be made to refer to an
instance of an object. This is done by assignment. You can assign an existing
object, or you can use the new operator.
Any new class will have a constructor , that is, a method whose name is the
name of the class. There can be many different constructors for the same class,
Objects as References
Search WWH ::




Custom Search