Java-向类添加参数
我试图在类的声明中添加一个参数 声明如下:Java-向类添加参数,java,class,parameters,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() { } } (这不起作用) 有什么建议吗?谢谢 您可能希望声明字段,并在
public static class TCP_Ping implements Runnable {
public void run() {
}
}
这就是我想做的:
public static class TCP_Ping(int a, String b) implements Runnable {
public void run() {
}
}
(这不起作用)
有什么建议吗?谢谢 您可能希望声明字段,并在构造函数中获取参数值,然后将参数保存到字段中:
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");
您可能希望声明字段,并在构造函数中获取参数值,然后将参数保存到字段:
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");
使用Scala!这得到了很好的支持
class TCP_Ping(a: Int, b: String) extends Runnable {
...
使用Scala!这得到了很好的支持
class TCP_Ping(a: Int, b: String) extends Runnable {
...
您不能在类标题上声明具体的参数(有类型参数之类的东西,但这并不是您所需要的)。您应该在类构造函数中声明参数,然后:
private int a;
private String b;
public TCP_Ping(int a, String b) {
this.a = a;
this.b = b;
}
您不能在类标题上声明具体的参数(有类型参数之类的东西,但这并不是您所需要的)。您应该在类构造函数中声明参数,然后:
private int a;
private String b;
public TCP_Ping(int a, String b) {
this.a = a;
this.b = b;
}
我建议你。关于您的问题:类不是静态的。方法、实例变量和初始值设定项块可以是静态的。然而,人们会滥用它。我建议你。关于您的问题:类不是静态的。方法、实例变量和初始值设定项块可以是静态的。然而,人们却滥用它。谢谢你的帮助,我永远也不会明白这一点!谢谢你的帮助,我永远也想不到!