Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use 'new' without 'xyz = new abc'

Tags:

java

libgdx

I have a class as follows:

package org.requiredinput.rpg1.desktop;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import org.requiredinput.rpg1.Rpg1;

public class DesktopLauncher {
    public static void main (String[] arg) {
        LwjglApplicationConfiguration config =
            new LwjglApplicationConfiguration();
        config.title = "Awesome rpg";
        config.width = 800;
        config.height = 480;
        new LwjglApplication(new Rpg1(), config);
    }   
}

My question is - on the last line, the new statement is used without being preceded by an =. What is being created? A new LwjglApplication object? Class?

And why doesn't it need to be instantiated like app = new LwjglApplication() for example?

like image 786
jdurston Avatar asked Dec 06 '22 23:12

jdurston


1 Answers

Your code creates a new object and doesn't give it a name, which means that it can't be used by main() afterwards. The code in the constructor will still run, and an object of type LwjglApplication will still be created. main() won't hold a reference to it, though.

This is just like when you call a function that returns a value without assigning it to a variable:

int foo() {
    System.out.println("Ron Paul 2016!");
    return 42;
}

public static void main(String... args) {
    foo(); // will print out "Ron Paul 2016!" (w/o quotes)
}

Here, nothing is being done with the return value from foo() but the println() call will still run.

This is commonly used when the constructor (in this case, that of LwjglApplication) has a beneficial side-effect. In your specific case, a window is being popped up as a result of the constructor. (As RafazZ said, you don't need to access the object that's being constructed because there are other ways to access it, provided through the third-party vendor's API.)

As Drew Kennedy mentioned in a comment, this pattern is also used for single-use objects.

Let's say you have a class that looks like this:

class Foo {
    void bar() {
        // stuff that requires being in an instance, such as...
        System.out.println(this.getClass());
    }

    public static void main(String... args) {
        (new Foo()).bar();
    }
}

Note that the program doesn't bother assigning a name to the newly created Foo object, since it's only being used for the benefit of calling its bar() method.

like image 66
APerson Avatar answered Dec 23 '22 02:12

APerson