【问题标题】:Java class extension [closed]Java类扩展[关闭]
【发布时间】:2011-12-29 04:51:33
【问题描述】:

我对 Java 类通过“扩展”继承的内容有点困惑。我有一个名为“Shape”的类,以及多个类,如 box、circle。盒子、圆圈等都具有三个共同的变量。需要 Shape 类来保存一个静态变量来计算类的数量。我在另一个类中也有一个 Shapes 向量。如果我声明一个圆形类,它会正确适合形状向量吗?我还注意到我可以这样做:

Shape shape = new Circle();  
ShapeVector.add(shape);  

我知道有接口,但它们是否可以包含我需要的静态变量,如果向量是由接口组成的,它将接受实现的类吗?

我尝试过接口、抽象类等,但我认为有太多组合需要测试,而且比提出问题要花更长的时间。

【问题讨论】:

  • I think there are too many combinations to test and it would take much longer than to ask a question. 好吧,实际做会比问问题更有效。
  • shapeVector 可以是Vector<Shape>。你需要吗?
  • 你的问题到底是什么?

标签: java interface abstract extends implements


【解决方案1】:

你需要这个:

package naishe.so.shapes;

import java.util.Vector;

public abstract class Shapes {
    private static int counter = 0;//Not really required, you could just count vector length
    private static final Vector<Shapes> shapesVector = new Vector<Shapes>();

    public Shapes() {
        counter++;
        shapesVector.add(this);
    }

    public Vector<Shapes> getAllShapes(){
        return shapesVector;
    }

    public int getCount(){
        return counter;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 2015-06-23
    • 2013-08-12
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多