Search code examples
javafx-8non-static

How is a non-static method accessed without an object?


I am new to JavaFX. In my following code, getHBox() is a non-static method is accessed without creating an object.

public class Main extends Application { 
    public void start(Stage primaryStage) {

        //Main m = new Main();

        try {
            BorderPane rootPane = new BorderPane();

            rootPane.setTop(getHBox());
            //rootPane.setTop(m.getHBox());

            Scene scene = new Scene(rootPane,400,400);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public HBox getHBox()
    {
        HBox hb = new HBox(15);
        hb.getChildren().add(new Button("Press"));
        return hb;
    }


    public static void main(String[] args) {
        launch(args);
    }
}

Now I have looked at the answers in Stackoverflow. Guys are talking something about class member. How is getHBox() method different from any other method? Please provide some explanation or direct me to an appropriate tutorial.


Solution

  • In my following code, getHBox() is a non-static method is accessed without creating an object.

    That is incorrect. As used in the code presented, getHBox() is invoked only by start(), another non-static method. As an instance method itself, start() must be invoked on an object (one instantiated by JavaFX, for instance). The invocation of getHBox() without designating a target object is implicitly directed to the same object, as if it were this.getHBox().

    How is getHBox() method different from any other method?

    It isn't, not in any relevant sense, nor is any of this specific to JavaFX.