Home > Blockchain >  Interface methods in a class that does not implement it?
Interface methods in a class that does not implement it?

Time:05-02

public interface Iterator<T> {

    // Returns true if the iterator is valid (points to an element), false otherwise.
    boolean isValid();

    // Returns the current element and moves forward. This method can only be called if the iterator is valid. If the iterator points to the last element, it becomes invalid after the call.
    T next();

    // Returns the current element and moves backwards. This method can only be called if the iterator is valid. If the iterator points to the first element, it becomes invalid after the call.
    T prev();
}

In a class that does not implement interface Iterator, how is it possible to create a method that returns Iterator<K>, when you can only create methods for an interface inside a class that implements it?

public class ABC<K> implements EFG<K>{
public Iterator<K> minIt() {
   //method body
   //return Iterator<K> variable 
}
}

The class ABC containing the method minIt() does not implement Iterator<T>

(No classes implement the interface Iterator <T> )

CodePudding user response:

Simple. By making a class that implements it. Note that you have a type that you came up with on your own and you named it Iterator. Given that java.util.Iterator exists, this is a really bad idea. You should pick another name.

public class ABC<K> implements EFG<K> {
  // Let's say this contains the items that can be iterated over.
  private List<K> list = new ArrayList<K>();

  class MyIterator implements my.pkg.Iterator<K> {
    private int position = 0;
    @Override public boolean isValid() {
      return position > -1 && position < list.size();
    }

    @Override public K next() {
      if (!isValid()) throw new NoSuchElementException();
      return list.get(position  );
    }

    @Override public K prev() {
      if (!isValid()) throw new NoSuchElementException();
      return list.get(position--);
    }
  }

  public Iterator<K> minIt() {
    return new MyIterator<K>();
  }
}

Note that classes that you put in classes can only be constructed in instance contexts within that class: They have a 'secret' field of your outer's type. Hence why the code in MyIterator can access the list field of your outer class.

Java has 'anonymous inner class literal' syntax which lets you shorten this: Instead of explicitly declaring class MyIterator, you can also write:

public Iterator<K> minIt() {
  return new your.pkg.Iterator<K>() {
    private int position = 0;
    @Override public boolean isValid() {
      // same code goes here as the previous snippet
    }
  };
}

This anonymous inner class form is a lot more common. It's just syntax sugar - a shorter way to write the same thing.

CodePudding user response:

You can use an Anonymous Class that implements the interface:

For instance:

interface Foo<T> {
    T foo();
}
class Bar<T>  {
   T t;
   public Foo<T> bar() {
       return new Foo<T>() { // <-- Anonymous class implementing `Foo`
            public T foo() {
                return t;
            }
       };
   }
}

Execution:

Bar<String> b = new Bar<>();
b.t = "hello"; // with a setter in real life
Foo<String> f = b.bar();
f.foo(); // will return "hello"

The other option which I think would be the most common is to use a method that returns the interface, for instance the list interface has an iterator() method even though it itself doesn't implements the Iterator interface.

List<String> list = new ArrayList<>();
Iterator<String> stringIterator = list.iterator();

Here's the implementation

  • Related