Question

I know of at least three ways. Pass the object through methods, directly refer to the object, or create a shortcut in the new class to the other class's object.

For example, I have a DataOutputStream toServer

in Main.java I declare (assume sock already declared)

    public static DataOutputStream toserver;
    public static void main() {
      toServer = new DataOutputStream(sock.getOutputStream() );
   }

But in another method I need to write to the server. Should I:

in Main.java

    WriteStuff.write(toServer);

then in WriteStuff.java

  public static void write(DataOutputStream toServer) {
    toServer.writeBytes("Foo\n");
  }

or in WriteStuff.java

    static DataOutputStream toServer = Main.toServer;
    public static void write() {
      toServer.writeBytes("Foo\n");
    }

or, again in WriteStuff.java

    Main.toServer.writeBytes("Foo\n");

What is the recommended convention? Pass the object when invoking the method, referencing the object directly by using Main.objectName or setting a shortcut in the class?

Which is faster?

Was it helpful?

Solution

You should write a getter for this value, so:

private static DataOutputStream toServer;

public static DataOutputStream getToServer() {
    return toServer;
}

OTHER TIPS

In the OOP the most important thing is avoid to broke the OO view. I cant see all your class map, for usually pass the instance is the best option.

But maybe you can use another approach, something like.

public interface IOutputHandler {
    public int write(Byte[] b);
}

public class Server {
     private OutputHandler oh;
     public void setOutputHandle(OutputHandler e) { this.oh = e; }
     public void Write(Byte[] b) { oh.write(b); }

  }

I don't know if my idea is enough clear with this example. In java is usually to pass a class that will handle some work.

Any question dont hesitate to ask ;P

You almost never want to make a data field public because then it is liable to being changed. Make the DataOutputStream private to the Main class, then have the main class have a method that uses the DataOutputStream. However, it sound like you are having another object(class) refer to the main class as an object. This may not(and probably wont) work because main is static there is no guarantee that the DataOutputStream was initialized. I would make another class that can directly deal with it. Static classes are difficult to deal with when they themselves are treated as objects doing an object's job. As for speed, unless you are calling this thing trillions of times, getting it through a method as opposed to directly getting the public variable has no bearing especially compared to the time that it takes for the DataOutputStream to do its work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top