2

I am trying to add a parameter at the declaration of a class.

Here is the declaration:

public static class TCP_Ping implements Runnable {

    public void run() {
    }

}

This is what I am trying to do:

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

    public void run() {
    }

}

(which doesn't work)

Any suggestions? thanks!

2

3 Answers 3

3

You probably want to declare fields, and get the values of the parameters in the constructor, and save the parameters to the fields:

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);
  }
}

Then you can create an instance of your class like this:

TCP_Ping ping = new TCP_Ping(5, "www.google.com");
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help, I would've never figured that out!
1

Use Scala! This is supported nicely.

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

Comments

0

You cannot declare concrete parameters on the class heading (there are such things as type parameters, but that's not what you need as it appears). You should declare your parameters in the class constructor then:

  private int a;
  private String b;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.