Java Reference
In-Depth Information
The runtime type of an object is what the object references. The compile-time
type of an object is what it is defined to be. For example, consider the follow-
ing code: FictionalCharacter c = new Superhero() . The runtime type of the c
object will be Superhero , while the compile-time type of the c object will be
FictionalCharacter .
Note that polymorphism uses the runtime type of an object to decide which version of a
method to call and ignores the compile-time type of the object. Alternatively, polymorphism
does not apply to static methods and the compile-time type of the object is used to determine
which version of the method to call.
The getClass method actually returns an object of type Class .Suchanobjectis
created for every class. One can call the getName() method to get the string description of
an object of type Class . Note as well the new syntax Superhero.class . The code refers to
the Class object for the Superhero class.
8.12 Cloning Objects
Once a fictional character is created, it may be nice to have the ability to clone them.
After all, we may need several Batmans to fight off the evil Joker. Inside the Object class, a
clone method is already defined. However, this method is defined as protected . Therefore,
Java forces us to override it as public before we can use it. The reason is that the default
clone method that is defined inside the Object class does not copy inner objects. Consider
the following simple example.
public class FictionalCharacter implements Cloneable {
private String name;
private Address address ;
public FictionalCharacter () {
} public FictionalCharacter(String name, Address address) {
this .name = name;
this . address = address ;
} public String toString() {
return name + " lives at " +address ;
protected Object clone () throws CloneNotSupportedException {
return super .clone();
}
}
{
private String streetName;
private int number ;
public Address ()
public class Address
{}
public Address( String streetName , int number)
{
this . streetName = streetName ;
this . number = number ;
}
 
Search WWH ::




Custom Search