2013-04-06 52 views
2

我想在類的聲明中添加一個參數。Java - 將參數添加到類

以下是聲明:

public static class TCP_Ping implements Runnable { 

    public void run() { 
    } 

} 

這就是我要做的:

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

    public void run() { 
    } 

} 

(不工作)

有什麼建議?謝謝!

+0

我建議你[Java中開始](http://docs.oracle.com/javase/tutorial/java/javaOO/index.html)。 關於您的問題:http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html – blint 2013-04-06 01:48:03

+0

類不是「靜態」。方法,實例變量和初始化塊可以是'static'。然而,人們濫用這一點。 – 2013-04-06 02:30:40

回答

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

感謝您的幫助,我永遠不會知道這件事! – 0101011 2013-04-06 01:57:44

1

使用Scala!這很好地支持。

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

你不能聲明在類標題的具體參數(有這樣的事情類型參數,但是這不是你所需要的是出現的話)。你應該在類的構造函數然後聲明您的參數:

private int a; 
    private String b; 

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