Java - 将参数添加到类

时间:2013-04-06 01:44:08

标签: java class parameters

我正在尝试在类的声明中添加参数。

以下是声明:

public static class TCP_Ping implements Runnable {

    public void run() {
    }

}

这就是我想要做的事情:

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

    public void run() {
    }

}

(不起作用)

有什么建议吗?谢谢!

3 个答案:

答案 0 :(得分: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");

答案 1 :(得分:1)

使用Scala!很好地支持了这一点。

class TCP_Ping(a: Int, b: String) extends Runnable {
    ...

答案 2 :(得分:0)

你不能在类标题上声明具体参数(有类型参数这样的东西,但这不是你需要的那样)。您应该在类构造函数中声明您的参数:

  private int a;
  private String b;

  public TCP_Ping(int a, String b) {
    this.a = a;
    this.b = b;
  }