Monday 7 January 2013

Chapter 2: Object Orientation: Polymorphism

Remember, any Java object that can pass more than one IS-A test can be
considered polymorphic.
Other than objects of type Object, all Java objects are
polymorphic in that they pass the IS-A test for their own type and for class Object.

Remember that the only way to access an object is through a reference variable,
and there are a few key things to remember about references:

- A reference variable can be of only one type, and once declared, that type
can never be changed (although the object it references can change).
- A reference is a variable, so it can be reassigned to other objects, (unless the
reference is declared final).
- A reference variable's type determines the methods that can be invoked on
the object the variable is referencing.
- A reference variable can refer to any object of the same type as the declared
reference, or—this is the big one—it can refer to any subtype of the
declared type!
- A reference variable can be declared as a class type or an interface type. If
the variable is declared as an interface type, it can reference any object of any
class that implements the interface.

class PlayerPiece extends GameShape, Animatable
{   // NO!
    // more code
}
So what else could you do? You already know the answer—create an Animatable
interface, and have only the GameShape subclasses that can be animated implement
that interface. Here's the interface:

public interface Animatable
{
    public void animate();
}

And here's the modified PlayerPiece class that implements the interface:

class PlayerPiece extends GameShape implements Animatable
{
    public void movePiece()
    {
        System.out.println("moving game piece");
    }

    public void animate()
    {
        System.out.println("animating...");
    }
    // more code
}

So now we have a PlayerPiece that passes the IS-A test for both the
GameShape class and the Animatable interface. That means a PlayerPiece can be
treated polymorphically as one of four things at any given time, depending on the
declared type of the reference variable:

- An Object (since any object inherits from Object)
- A GameShape (since PlayerPiece extends GameShape)
- A PlayerPiece (since that's what it really is)
- An Animatable (since PlayerPiece implements Animatable)

PlayerPiece player = new PlayerPiece();
Object o = player;
GameShape shape = player;
Animatable mover = player;

Polymorphic method invocations apply only to instance methods. You can
always refer to an object with a more general reference variable type (a superclass
or interface), but at runtime, the ONLY things that are dynamically selected
based on the actual object (rather than the reference type) are instance methods.
Not static methods. Not variables. Only overridden instance methods are
dynamically invoked based on the real object's type.



 

No comments:

Post a Comment