Site hosted by Angelfire.com: Build your free website today!
 

Assigning Subclass to Superclass

You can put an object into a more general type

abstract class GrObj {
    int x, y;
    public void moveTo(int x, int y) {
        this.x = x;
        this.y = y;
    }
    abstract void draw();
}
class Rect extends GrObj {
    void draw() {
        System.out.println(toString());
    }
}
class Circle extends GrObj {
    void draw() {
        System.out.println(toString());
    }
}
public class Main {
    public static void main(String[] args) {
        GObj[] gobj = { new Rect(), new Circle() };
        for (int i = 0; i < gobj.length; i++)
            gobj[i].draw();  // Polymorphism
    }
}
Polymorphism

Polymorphism provides one of the most useful programming techniques of the object-oriented paradigm. Polymorphism is the ability to treat an object of any subclass of a base class as if it were an object of the base class. A base class has, therefore, many forms: the base class itself, and any of its subclasses.