覆盖从库到不同项目的方法

时间:2013-03-12 17:48:57

标签: java android eclipse shared-libraries method-overriding

我将我的主代码设置为一个项目,其他两个项目(lite和pro)引用它。

这就是我希望Quiz类查找lite的方式:

class Quiz {
    public Quiz {
        object1();
        object2();
        object3();
        object4();
    }
}

这就是我希望Quiz课程寻找专业人士的方式:

class Quiz {
    public Quiz {
        object1();
        object2();
        object3();
        object4();
        object5();
        object6();
        object7();
        object8();
    }
}

为了实现这一点,我是否需要将类Quiz设置为在库中进行抽象,然后定义它们,但是我想在lite和pro项目中进行抽象?或者我应该将库定义为上面的第一个Quiz示例,然后尝试在专业版中以某种方式覆盖它?

修改

根据下面的评论,这里是实际代码的片段。

public class Quiz {

    ArrayList<Question> exodus = new ArrayList<Question>(200);

    public Quiz() {

        exodus.add(new Question("Aaron", "Abraham", "Jacob", "Joseph", 0, "What was the name of Moses' brother?", -1, "Exodus 7:1-2"));
        exodus.add(new Question("5", "10", "7", "12", 1, "How many plagues did God send on Egypt?", -1, "Exodus 7-12"));
        exodus.add(new Question("Pharaoh's maid", "Pharaoh's wife", "Pharaoh's daughter", "Pharaoh's mother", 2, "Who found baby Moses in a basket along the riverside of the Nile river?", -1, "Exodus 2:3-5"));
        exodus.add(new Question("Hail", "Frogs", "Boils", "Flies", 1, "What was the 2nd plague?", -1, "Exodus 8:2"));
        exodus.add(new Question("Darkness for 3 days", "All water turns to blood", "Boils", "Flies", 3, "What was the 4th plague?", -1, "Exodus 8:24"));
        exodus.add(new Question("Frogs", "Boils", "Hail", "Lice", 1, "What was the 6th plague?", -1, "Exodus 9:10"));
        exodus.add(new Question("Boils", "All livestock dies", "Lice", "Locusts", 3, "What was the 8th plague?", -1, "Exodus 10:14"));
        exodus.add(new Question("Darkness for 3 days", "Death of firstborn", "All water turns to blood", "All livestock dies", 1, "What was the 10th plague?", -1, "Exodus 12:29"));
}

2 个答案:

答案 0 :(得分:2)

假设您指的是构造函数,因为问题不明确

class Quiz {
    public Quiz (){
        object1();
        object2();
        object3();
        object4();
    }
}

class QuizForPro extends Quiz{
    public QuizForPro() {
        super();
        object5();
        object6();
        object7();
        object8();
    }
}

您可以扩展其他库Quiz中的Pro,然后提供对您的库有意义的更专业的实现。这就是OOP中提供专业化的原因,因此您可以扩展父类功能并提供一些额外的行为(在您的情况下,在arraylist中添加更多元素)。

<强>更新 查看您正在使用构造函数添加问题的代码段,这将是一个不好的地方。

您应该提供类似addQuestion(...), removeQuestion(...), clearQuestions(...)的方法。这些将更有意义。

答案 1 :(得分:1)

同意Narendra的回答,它应该有效。但是,我猜想下面的设计应该足够了。 {再次取决于最终产品的实际要求}

使用数组列表定义作为类来测试,以存储数据,但在构造函数中没有初始化。它提供了添加大量问题的方法。

public final class Quiz {
  ArrayList<Question> exodus = new ArrayList<Question>(200);
  public Quiz() { }
  public addQuestions(List<Question> questions) {
     // ... implementation here ... 
  }
}

我将把lite和pro作为成员初始化在客户端类中,或者提供一个QuizHelper类来创建这两种类型的对象并返回它。