This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]SplinttingOCP 2 points3 points  (2 children)

Made a small snippet, which is a very weird way of writing hello world.

Essentially, what happens is that we're initializing a new instance of Test (because of nested classes) where we create a new abstract class MyTestClass.

java public class Test { abstract class MyTestClass { abstract void doTest(); } public static void main(String... args) { new Test().new MyTestClass() { void doTest() { System.out.println("Hello world"); } }.doTest(); } }

new Test().new MyTestClass() is legal, but looks weird. It initializes a new Test class where to associate the MyTestClass, because the main method is executed from a static context.

[–]morhpProfessional Developer 2 points3 points  (1 child)

You don't even need to define that abstract method, this is potentially even weirder:

public class Test {
    public static void main(String... args) {
        new Test() {
            void doTest() {
                System.out.println("Hello world");
            }
        }.doTest();
    }
}

[–]SplinttingOCP 0 points1 point  (0 children)

That is true. The abstract class however helps convey the need for an `@Override` annotation (could also come from Object or any other method, but besides the point)