10/03/2008

Inheritance and Polymorphism

Sub classes can extend the super class using the keyword extends.

Basic Structure
class Animal {
    ...
}

class Tiger extends Animal {
    ...
}


is-a relation

Animal obj = new Tiger(); --> Tiger is-a Animal

example)

class Animal {
    String getValue() { return "Animal";}
}

class Tiger extends Animal {
    String getValue() { return "Tiger";}
    void func() { System.out.println("Tiger");}
}


Animal obj = new Tiger();

Polymorphism
obj.value cannot reach Anmal's getValue method because the getValue method is overridden in the Tiger class.

Override
In the above example there are two same-name methods. the getValue method in the sub class overrides the getValue method in the super class.

obj is an Animal type object, thus obj cannot access any method in the Tiger class except those overridden methods.
If you want to reach out to those methods in the sub class from the obj, Animal type obj can be casted to Tiger type.
example
(Tiger)obj.func();