Use 'new' without 'xyz = new abc'

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 - the operator newwithout the previous is used in the last line =. What is being created? New facility LwjglApplication? Class?

And why doesn’t it need to be created, for example app = new LwjglApplication()?

+4
source share
5 answers

Your code creates a new object and immediately discards its link to it.

This happens 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)
}

Nothing is done here with the return value from foo(), but the call println()will still be executed (and your code will be compiled and life will continue).

, ( , LwjglApplication) . . ( RafazZ , , , , API- .)

, .

, , :

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();
    }
}

, Foo, bar().

+11

BadLogic, LwjglApplication . , - , , . - API, (BadLogic ).

LwjglApplication.

TL; DR UPDATE: , DesktopLauncher, OpenGL, new LwjglApplication. , OpenGL, , , DesktopLauncher.

+2

LwjglApplication, .

, . .

+1

, . , LwjglApplication.

, , . , , , Singleton.

+1

new MyClass() - Java. - , . nuanses, .

So new - .

Java ( ).

, , . , - .

If the return value is an object and it really is not used, then it will be garbage collected later, as with every unused object.

Example:

package tests;

public class Runner {

    public static class Line {
        public Line(String line) {
            System.out.println(line);
        }
    }

    public static void main(String[] args) {

        new Line("Hello world");

    }

}
0
source

All Articles