Elo Benc
Elo Benc

Reputation: 35

Using object in another class

I want to use inst in another class SubscribeTables() I need it with all of its data. I tried to make a getter in Main() but it didnt work. Maybe i can pass it to another class somehow? Can someone help me with it?

Lets say i need to call inst.isConnected() in SubscribeTables()

public class Main {
    public static void main(String[] args) throws IOException {

      // Setup NT4 Client
      NetworkTableInstance inst = NetworkTableInstance.getDefault();
      inst.startClient4("FRC Stat Track");
      selectNetworkTablesIP(inst, 5883);
      // Connects after ~100ms


      new SubscribeTables();
}

Upvotes: 0

Views: 63

Answers (3)

Enowneb
Enowneb

Reputation: 1037

So to consolidate, in terms of code, your SubscribeTables class should look like this:

public class SubscribeTables {
    private NetworkTableInstance instance;

    // Make a constructor to take NetworkTableInstance
    public SubscribeTables(NetworkTableInstance instance) {
        this.instance = instance;
    }

    public void function() {
        // Use the NetworkTableInstance for every function in this Class
        boolean isConnected = instance.isConnected();
    }
}

And the way to create a SubscribeTables object:

SubscribeTables tables = new SubscribeTables(inst);

Upvotes: 1

Oleksandr Myronets
Oleksandr Myronets

Reputation: 98

You can supply link of object A(type NetworkTableInstance) to object B(type SubscribeTables) either by argument in constructor or by argument in setter method. In both cases SubscribeTables class should have field of type NetworkTableInstance to put NetworkTableInstance object from constructor or setter arguments into the field.

Upvotes: 0

Sudarshana Gurusinghe
Sudarshana Gurusinghe

Reputation: 46

The scope of NetworkTableInstance inst is limited to the lifecycle of main method as your new class is not aware. You have 2 options if you still want to do it in this way - but not recommened.

  1. Pass the instance of NetworkTableInstance as a constructor paramater to SubscribeTables

  2. Pass the instance of NetworkTableInstance to the respective methods as a method parameter you need to call on SubscribeTables

Upvotes: 0

Related Questions