首页 > 代码库 > JAVA多态示例

JAVA多态示例

这多态,我觉得是最利害的。在开发大型程序中。

但,也是需要经过足够多的实践经验才能随心利用的。

class Quadrangle{
    private Quadrangle[] qtest = new Quadrangle[6];
    private int nextIndex = 0;
    public void draw(Quadrangle q){
        if(nextIndex < qtest.length){
            qtest[nextIndex] = q;
            System.out.println(nextIndex);
            nextIndex++;
        }
    }
    public static void main(String[] args){
        Quadrangle q = new Quadrangle();
        q.draw(new Square());
        q.draw(new Parallelogram());
    }
}
class Square extends Quadrangle{
    public Square(){
    System.out.println("this is a Square class.");
    }
}
class Parallelogram extends Quadrangle{
    public Parallelogram(){
    System.out.println("this is a Parallelogram class.");
    }
}

this is a Square class.
0
this is a Parallelogram class.
1