2013-04-06 38 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; 
    }