2

クラスの宣言にパラメーターを追加しようとしています。

宣言は次のとおりです。

public static class TCP_Ping implements Runnable {

    public void run() {
    }

}

これは私がやろうとしていることです:

public static class TCP_Ping(int a, String b) implements Runnable {

    public void run() {
    }

}

(これは機能しません)

助言がありますか?ありがとう!

4

3 に答える 3

3

おそらく、フィールドを宣言し、コンストラクターでパラメーターの値を取得し、パラメーターをフィールドに保存する必要があります。

public static class TCP_Ping implements Runnable {
  // these are the fields:
  private final int a;
  private final String b;

  // this is the constructor, that takes parameters
  public TCP_Ping(final int a, final String b) {
    // here you save the parameters to the fields
    this.a = a;
    this.b = b;
  }

  // and here (or in any other method you create) you can use the fields:
  @Override public void run() {
    System.out.println("a: " + a);
    System.out.println("b: " + b);
  }
}

次に、次のようにクラスのインスタンスを作成できます。

TCP_Ping ping = new TCP_Ping(5, "www.google.com");
于 2013-04-06T01:46:29.113 に答える
1

スカラを使おう!これはうまくサポートされています。

class TCP_Ping(a: Int, b: String) extends Runnable {
    ...
于 2013-04-06T01:46:44.160 に答える
0

クラス見出しで具体的なパラメーターを宣言することはできません (型パラメーターなどがありますが、それは必要なものではありません)。次に、クラス コンストラクターでパラメーターを宣言する必要があります。

  private int a;
  private String b;

  public TCP_Ping(int a, String b) {
    this.a = a;
    this.b = b;
  }
于 2013-04-06T01:48:50.680 に答える