Question

** not sure if its obvious, but I am writing java

I have been trying to complete an assignment for a class of mine which requires me to implement the ListIterator<String> interface for a class. I do not wish to implement remove(), add(), or set(), which are the optional methods for the interface. But now that it is implemented, Eclipse is giving me errors saying I need to implement those methods. Does anyone know why that is or how I can solve that? Thank you in advance for your help.

Was it helpful?

Solution

They're not really optional.

You have to provide some sort of implementation, but it's common to provide an implementation that just throws an exception:

public void remove() {
    throw new UnsupportedOperationException();
}

In some situations it might also be reasonable to provide a "do-nothing" implementation:

public void remove() {
    // Can't remove...
}

If you do either of these, it's a good idea to document that you've done it.

If you make this an abstract class, then you don't have to implement the methods in this specific class. But at some point down the class hierarchy, you have to implement a concrete class with all the methods. Nothing actually happens until you instantiate your class in an instance, and you can't do that with an abstract class.

OTHER TIPS

Interface methods are not optional, but rather insure that the class implementing the given interface implements all its methods unless it is an abstract class. When a class implements a certain interface it can be referred to as the type of the interface according to the concept of polymorphism in Java.

Example below:

public interface Herbiverous {
    void eatsPlants();
}

public class Human implements Herbiverous{
    public void eatsPlants() {
       System.out.println("I eat plants");
    }

    public static void main(String[]args) {
        Herbiverous h = new Human();
        //in which case you can only apply the methods of the interface
        h.eatsPlants();
    }
}

Hope this was insightful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top