So far, we've seen primitive data like integers and booleans, but sometimes we want to treat a collection of data as one entity and carry it around as a single unit. This idea is called compound data.
Each class can have
Couple
public class Couple { // Instance variables String husband; String wife; int weddingYear; // Constructor Couple(String man, String woman, int yearMarried) { husband = man; wife = woman; weddingYear = yearMarried; } // Accessors public String getHusband() { return husband; } public String getWife() { return wife; } public int getWeddingYear() { return weddingYear; } // toString method (used by Java to convert an object into a String) public String toString() { return husband + " and " + wife + " were married in " + yearMarried; } }Now, in order to create an instance of the class, we use the operator
new
as follows:
Couple goldmans; goldmans = new Couple("Ken", "Sally", 1984);The first line declares a variable
goldmans
whose
type is a reference to a Couple
object.
This variable initially has the value null
because it does not yet refer to any object.
The expression new Couple("Ken", "Sally", 1984)
causes the creation of a new Couple object somewhere in the
heap memory. The constructor is called with the supplied
parameters, and the instance variables are initialized
accordingly.
Then the assignment makes the value of the variable
goldmans
be a reference to the newly created
object. (You can think of the reference variable as
containing the memory address of the object.) Note that, as
with other variables, declaration and assignment can appear on
one line:
Couple goldmans = new Couple("Ken", "Sally", 1984);Given the reference variable, we can invoke methods on the object using the "dot" notation we've been using for the
System
and Math
classes. For
example, the expression goldman.getWife()
would
evaluate to the string "Sally"
.
Within a program, you could use the Couple
class
as follows:
// Declaration and initialization Couple goldmans = new Couple("Ken", "Sally", 1984); System.out.println("The husband is " + goldmans.getHusband()); System.out.println(goldmans.getWife() + " is his wife."); System.out.println(goldmans.toString()); System.out.println("" + goldmans);(In the last line, Java sees that a conversion from
Couple
to String
is necessary and
automatically calls goldmans.toString()
.)What would happen in the following?
Couple clintons; System.out.println("Bill and Hillary were married in " + clintons.getWeddingYear());Since the variable
clintons
is an uninitialized
reference variable, its value is null
. It does not
refer to any object. Therefore, the expression
clintons.getWeddingYear()
cannot be evaluated.If you're lucky, the compiler will detect this and inform you that
Variable clintons
may not be initialized.
Otherwise, if the compiler does not detect a null reference,
you'll get an error at run time,
java.lang.NullPointerException
, and it will show
you the line number where the exception occurred.