Java Reference
In-Depth Information
Example 3.28
The
Person
class
class
Person
{
String name;
Address addr;
public
Person(String name, Address addr)
{
this.name = name;
this.addr = addr;
} // constructor
// ... lots more code is here
public String getName()
{
return name;
}
}
Example 3.29
An example use of polymorphism
//...
Sample labwork = new Sample(petridish);
Employee tech = new Employee(newguy, 27);
Identifiable stuff;
//...
if (mode) {
stuff = labwork;
} else {
stuff = tech;
}
id = stuff.getID();
The key point here is when the call is made to
getID()
. The compiler
can't know at compile time which object will be referred to by
stuff
, so it
doesn't know whose
getID()
method will be called. But don't worry—it works