0

以前受けた就職面接試験の質問でした。なぜ誰かがこれをやりたいのか、それが可能かどうかさえわかりませんが、誰かがこのコレクションにどのようにデータを入力するのでしょうか?

Collection<MyLinks> links = null;    //Populate this variable

public interface MyLinks() {
    //Method headers only
}

MyLinks オブジェクトをインスタンス化できない場合、このコレクションを埋めるにはどうすればよいですか? これはひっかけ問題でしたか?

4

6 に答える 6

2

インターフェイスを実装するオブジェクトでコレクションを埋めます。

public interface MyInterface {
  int getANumber();
}

public class RandomNumberGenerator implements MyInterface {
  public int getANumber() {
    return 4; // choosen by a fair dice roll
  }
}

Collection<MyInterface> collection = new ArrayList<MyInterface>();
collection.add(new RandomNumberGenerator());

ヒント: 乱数ジェネレーターが必要な場合は、コードをコピーしないでください。

于 2013-02-21T20:48:00.917 に答える
1

このようなコレクションには、そのインターフェイスを実装するクラスを持つ任意のオブジェクトを格納できます。オブジェクトは、それらのクラスがそのインターフェイスを実装している限り、異なるクラス (匿名クラスであっても) であることができます。

class ConcreteMyLinks implements MyLinks...
class ConcreteMyLinks2 implements MyLinks...

ConcreteMyLinks obj = new ConcreteMyLinks();
ConcreteMyLinks2 obj2 = new ConcreteMyLinks2();
collection.add(obj);
collection.add(obj2);
collection.add(new MyLinks() {  /* implement interface here */ });
于 2013-02-21T20:46:44.057 に答える
1

インターフェイスを実装するクラスを作成し、それを入力します。

于 2013-02-21T20:47:06.660 に答える
0

上記の解決策は正しいです。匿名クラスを使用することもできます。

MyInterface object = new MyInterface() {
   //here override interfaces' methods
}
于 2013-02-21T20:51:47.653 に答える
0
  1. そのインターフェイスを実装する具象クラスのインスタンスを作成し、それをコレクションに追加できます。

    collection.add(new MyConcreteLinks());
    
  2. 次のような匿名クラス インスタンスを作成できます。

    collection.add(new MyLinks() { /*overide mylinks method*/});
    
于 2013-02-21T20:52:11.100 に答える
0

この仲間を試してください:

    links = new ArrayList<MyLinks>();
    links.add(new MyLinks() { });

幸運を!

于 2013-02-21T20:48:42.810 に答える