我在 UML 中有以下架构:
Lecturer----implements-----Teaches (interface)
|
Assistant-----implements-----|
所以我希望我的界面有一个类(class)列表,老师可以讲授,助理也可以讲授。到目前为止我有以下代码:
public interface Teaches{
public String[] coursesList=new String[3];
}
//类(class)教师将类(class)输入到类(class)列表中,如下所示:
public class Teacher{
//////
private int i;
//currently omitting some arguments in the constructor
public Teacher(){
i=1;
}
addCourse(String course){
coursesList[i]=course;
i++;
}
助理类(class)也完成了相同的过程,但是当我打印数据时,我注意到只列出了老师的类(class),而不是助理的类(class)。有什么办法可以避免这种情况发生吗?
谢谢
最佳答案
默认情况下,接口(interface)定义中的所有变量都是static
和final
。 Section 9.3 of the JLS covers this :
Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.
这意味着任何实现 Teaches
接口(interface)的东西都可以访问相同的static
数组coursesList
。您的 Teacher
对象可能会覆盖 coursesList
数组的元素。
您应该将 Teaches
接口(interface)更改为抽象类,以便它可以拥有自己的实例变量 courseList
,每个具体子类都可以访问该变量。
关于java - 保存数组的接口(interface),由不同的类使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23918577/