簡體   English   中英

class中的接口方法沒有實現嗎?

[英]Interface methods in a class that does not implement it?

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();
}

在不實現接口 Iterator 的 class 中,當您只能為實現它的 class 中的接口創建方法時,如何創建返回Iterator<K>的方法?

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

class 包含方法minIt()ABC未實現Iterator<T>

(沒有類實現接口Iterator <T>

簡單的。 通過制作一個 class 來實現它。 請注意,您有一個自己想出的類型,並將其命名為Iterator 鑒於java.util.Iterator存在,這是一個非常糟糕的主意。 你應該選擇另一個名字。

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>();
  }
}

請注意,您放入類中的類只能在該 class 內的實例上下文中構造:它們具有外部類型的“秘密”字段。 因此,為什么 MyIterator 中的代碼可以訪問外部 class 的list字段。

Java 具有“匿名內部 class 字面量”語法,可讓您縮短此句法:除了顯式聲明class MyIterator ,您還可以編寫:

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
    }
  };
}

這種匿名內部 class 形式更為常見。 它只是語法糖——一種編寫相同內容的更短方式。

您可以使用實現接口的匿名 Class

例如:

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;
            }
       };
   }
}

執行:

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

我認為最常見的另一個選項是使用返回接口的方法,例如列表接口有一個iterator()方法,即使它本身沒有實現Iterator接口。

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

這是實現

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM