Vikas Vikas - 4 months ago 15
Java Question

What is this structure in Java that behaves like a method but has no name/parameters or identifiers?

After declaring Socket mSocket, there's this bracket structure (w/ the try catch block) that operates before onCreate(). What is it and how does it work? Is it a method, and how/when is it called? Thanks!

import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;

private Socket mSocket;
{
try {
mSocket = IO.socket("http://chat.socket.io");
} catch (URISyntaxException e) {}
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSocket.connect();
}

Answer

It just a way to initializing your field in case you require something more complex.

Here is a quote from Java Doc:

As you have seen, you can often provide an initial value for a field in its declaration:

public class BedAndBreakfast {

    // initialize to 10
    public static int capacity = 10;

    // initialize to false
    private boolean full = false; 
}

This works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Example usage:

{
    // whatever code is needed for initialization goes here
}

Another approach would be final methods.

class Whatever {
    private varType myVar = initializeInstanceVariable();

    protected final varType initializeInstanceVariable() {
        // initialization code goes here
    }
}
Comments