0

I have the following schema in UML:

Lecturer----implements-----Teaches (interface)
                             |   
Assistant-----implements-----|

so I want my interface to have a list of Courses that the teacher could lecture and that the assistant could do it also. So far I have the following code:

public interface Teaches{
      public String[] coursesList=new String[3];
}

//class Teacher enters couses into the coursesList like this:

public class Teacher{
      //////
      private int i;
      //currently omitting some arguments in the constructor
      public Teacher(){
              i=1;
      }
      addCourse(String course){
              coursesList[i]=course;
              i++;
}

the same procedure is done by the Assistant class, but when I print the data I have noticed that only lists me the courses from the teacher and not from assistant. Is there any way that situation does not happen?

Thanks

3
  • 2
    You can't have instance variables in an interface. Commented May 28, 2014 at 17:54
  • 1
    Interfaces shoul not carry attributes afaik. Commented May 28, 2014 at 17:55
  • What's the difference between a Lecturer and a Teacher? Commented May 28, 2014 at 17:55

2 Answers 2

2

By default, all variables in an interface definition are static and 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.

That means that anything that implements the Teaches interface has access to the same static array coursesList. Your Teacher object is likely overwriting the elements of the coursesList array.

You should change your Teaches interface into an abstract class, so that it can have its own instance variable courseList that each individual concrete subclass can access.

Sign up to request clarification or add additional context in comments.

1 Comment

... Or maybe create a base class BaseTeacher (which may or may not be abstract). The bottom line is coursesList does NOT belong in an interface.
1

Interfaces cannot have data, just specfication.

If you want your classes to inherit a String[] coursesList, you'd rather make the class abstract

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.