2 ms·
> I would have liked there to be support for inline subclasses that can be called from within the same anonymous class environment, but I can see how that would
by pron 4y ago
> I would have liked there to be support for inline subclasses that can be called from within the same anonymous class environment, but I can see how that would create ambiguity with existing code.
Not sure what you mean by "inline subclasses", but an anonymous main class can contain class declarations -- just as classes, named or anonymous can today. This file would be a complete legal program:
record Foo(int x, int y) {}
class Bar { static void print(Foo f) { System.out.println(f); } }
void main() {
Bar.print(makeFoo());
}
Foo makeFoo() { return new Foo(3, 4); }
- OkayPhysicist 4y agoAh, in that case I take that back. I definitely thought you needed to be able to reference the parent class in order to call (classes defined within other classes, can't remember the nomenclature).
- pron 4y agoThere's no need to do that from within the class. It all works just as it would in an anonymous class today. This code, that employs an anonymous class, is valid Java today (you can paste it into jshell): new Object() { record Foo(int x, int y) {} class Bar { static void print(Foo f) { System.out.println(f); } } void main() { Bar.print(makeFoo()); } Foo makeFoo() { return new Foo(3, 4); } }.main(); This JEP merely brings together two existing ideas in Java: 1. Anonymous classes 2. Unnamed instances of programming-in-the-large concepts are implicitly provided for you (today this is the case only for packages and modules). There are no new changes or restrictions to Java syntax in the body of the anonymous class.