8 ms·
JEP 445: Flexible Main Methods and Anonymous Main Classes (Preview)
- mfiguiere 4y agoThe timeline of its promotion from draft status along with several mentions of JDK 21 in the provided examples make it likely to ship with JDK 21 in September.
- kasperni 4y agoAs a preview feature
- hyperpape 4y agoThe section on how the main method will be resolved is a bit painful. I can’t see a way around it that doesn’t do nasty things for composability and/or backwards compatibility, but it does give me pause. Any situation where you have to ask “which main method in this class will be executed?” is quite bad.
- pron 4y agoWhich is why, as part of designing this feature, we ran a corpus search to see what portion of classes with a main method have another main that would be a candidate entry point under this JEP. It was negligible. Additionally, we'll give a linter warning if there's more than one candidate.
- pgwhalen 4y agoAs much as it's a crutch in programming language design to say "we don't have to worry too much about the lack of ergonomics in this case, it would be such bad code if this edge case gets run into in the first place," this seems like one of those situations. Another point: IDEs will be able to tell you which main method will get chosen, which should eliminate at least some uncertainty.
- WhereIsTheTruth 4y agoKotlin and the likes proved them wrong Glad to see them evolving faster as a result
- java-man 4y agoI feel like this is introducing a change for the sake of change, solving a problem which does not exist. The price of this change is very real: adding complexity and bugs to all the tools, IDEs, code analyzers and the like. There is negative net benefit to pretty much everyone involved, and for what?
- Pet_Ant 4y agoThat is literally what is addressed by the first section of the document. Both in "Summary" and in "Goals" > Far from using a separate dialect of Java, students can write streamlined declarations for single-class programs and then seamlessly expand their programs to use more advanced features as their skills grow. I remember when I started with Java 20 years we had a special IDE (BlueJ maybe? DrJava?) that wrapped the main class so that <code>System.out.println("Hello world");</code> was a complete program. So that is clearly > Do not introduce a separate beginner's dialect of Java. Perhaps this is in response to Python growing as an initial programming language (IMHO wrongly because types are fundamental to thinking about programming). They also mention: > Reduce the ceremony of writing simple programs such as scripts and command-line utilities. You can question the merits or trade-offs, but it's very clearly spelled out. > Reduce the ceremony of writing simple programs such as scripts and command-line utilities.
- java-man 4y agoIs this really what students struggle with? I think it is important to be able to determine the root cause of a problem first. Do students find difficult to write "public static void main(String[] args)" or do they find difficulty understanding the concepts of a public method, a static method, a void method? Perhaps then we should focus on teaching these concepts, which are essential to java, first, instead of undermining the core of the language and the platform. Neither "goals" nor "summary" can explain away why this can solve the problem this JEP purports to solve. This is my opinion, of course.
- pron 4y ago> Perhaps then we should focus on teaching these concepts, which are essential to java, first. As the JEP explains, this change does make the concepts of classes and access modifiers easier to teach by allowing the teacher to postpone their introduction to a point in time when they're actually useful and can be understood. Access control, static, and class declarations are only meaningful once you have other classes and/or objects interacting with your code. We don't want to force teachers to teach programming in the large early because many of them told us they don't do that anyway. > instead of undermining the core of the language and the platform The syntax and concepts of anonymous classes are unchanged. Providing an unnamed class, implicitly, when a class isn't needed is consistent with how we already provide an unnamed package and an unnamed module implicitly when they're not needed.
- yarg 4y agoAll I can think coming away from this is: This still seems pretty useless, It'd be nice if java could allow for static interface methods. interface Program { static void main(String...args); } And then I digressed - heavily. There have been several times when I've wanted static methods that apply to the specific class - although many of the situations could be shoehorned into a constructor, it's not the best. You'd also want something like a 'This' meta-class keyword. interface Foo extends Comparable<This> { static This(A argA, B argB); static This difference(This v0, This v1); static int compare(This v0, This v1); default int compareTo(This other){ return compare(v0, v1); } } /* I want to return an instance of my class' own type (defined in a subclass an so unknown), so I pass every implementation itself as its own generic parameter. */ interface Why<W extends Why<W>> implements Comparable<W>{ W someManipulation(); } class Foo implements Why<Foo> { @Override Foo someManipulation(){ .... } } To be honest, I think I reacted to how robust this does not feel. It also blurs the line between static and instance syntax/functionality in a way that does not seem useful - and given that this is intended to reduce barriers to entry, is quite probably harmfully confusing.
- yarg 4y agoA better example of what I'm thinking (assuming these interfaces are in java.lang to allow for safe operator overloading): interface Summable { static This sum(This v0, This v1); } interface Subtractable { static This difference(This v0, This v1); } interface Divisible { static This quotient(This v0, This v1); } interface Mulitiplicable { static This product(This v0, This v1); } interface Number extends Summable, Subtractable, Divisible, Multiplicable; void <N extends Number> doThings(N v0, N v1){ N sum = v0 + v1; }
- evntdrvn 4y agoThe .NET team just added static interface members in C# 11, because they themselves had this need in order to create System.Numerics: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tu... https://learn.microsoft.com/en-us/dotnet/api/system.numerics?view=net-7.0#interfaces https://learn.microsoft.com/en-us/dotnet/api/system.numerics...
- clhodapp 4y agoI'd love to see them follow with full-blown package-level methods and fields at some point (as alluded to in the alternatives) but this seems like a great minimal change to address a real pain point with learning to code in Java.
- johnfn 4y agoPretty nice! Makes me wonder why they didn't take the final step and say that anything not inside `void main()` gets bundled up into an implicit function run first.
- djur 4y agoIt's addressed near the end: > Eliminating the main method altogether may seem like the natural next step, but it would work against the goal of gracefully evolving a first Java program to a larger one and would impose some non-obvious restrictions (see below): The "see below" boils down to there being a number of differences between how class-level and method-level code units (fields vs. variables) work, and blurring the line there isn't worth the minor additional effort of writing a main() method.
- hyperpape 4y agoQuestion that just now occurs to me: what if you have the follow class and invoke it? (typing without an IDE, forgive any compilation errors). I can imagine answers, but I’m not sure if the JEP explains which one will happen (genuinely unsure, I could’ve easily missed it). public class Foo { int x; public Foo(int x) { this.x = x; } void main() { System.out.println(x); } }
- pron 4y agoThe JEP says: > If a launched class has no static main method but has a non-private zero-parameter constructor ... and a non-private instance main method, then construct an instance of the class... [and] invoke the instance main method Your class doesn't have a zero-parameter constructor nor a suitable static main, so launching it as a program will fail (as it would today).
- specialist 4y agoLove it. Don't forget to support shebang. So we can finally use Java as a system scripting language. Maybe something like: #!/usr/bin/env java And maybe also allow specifying the runtime version: #!/usr/bin/env java-12.0.*
- carimura 4y agoLike this? https://dev.java/learn/single-file-program/ https://dev.java/learn/single-file-program/
- specialist 4y agoAha! Exactly like that. Nicely spotted.
- oweiler 4y agoJBang can do this: https://www.jbang.dev https://www.jbang.dev
- specialist 4y agoLooks amazing. Thanks! When I write the Getting Started for my (FOSS) library, I'll definitely make a JBang variant. (Gitpod and SDKMAN also look interesting.) The use of Groovy's @Grab et al is also interesting. I'm eager to see how the dependency, imports, modules, local repo cache story, etc story plays out. Even after all this time, the Java stack still hasn't found its sweet spot. Though I confess I don't know what that'd look like.
- tpoacher 4y agoMy 2¢ is that this will probably do more to confuse than to enlighten students. Getting your "first" program off the ground quickly is good, but only if it doesn't cripple your understanding of what's going on for months later. For me the main thing that confuses the crap out of students is how people who introduce java tend to take "shortcuts" and bundle all functionality under the sun into a single class, which then also has a main method at the end. Presumably this is done so that everything is a single file, or can fit in a single presentation slide. But then suddenly your main looks like it's calling its container class to make objects of "itself" that contain new "mains", at which point your student has lost the plot completely. The simplest thing to keep things clean and self explanatory is to separate everything that isn't "main-related" into its own class (preferably another file if public), and then keep a nice clean public class called "Main" which contains 'only' the main method. Then you get to explain nicely how public classes have their own files, and if you attempt to run this class from the terminal, java will look for the 'main' function, and how this therefore needs to be public, static because you're running it straight from the class, void because you don't depend on it returning a value (which also makes for a nice intermission on how c returns status as an int, but java has a special mechanism instead). I do agree with the end of the JEP though; if you want to teach simple snippets like System.out.println, jshell is a nice way to do this, if you want to delay talking about classes and their methods.
- pron 4y ago> But then suddenly your main looks like it's calling its container class to make objects of "itself" that contain new "mains", at which point your student has lost the plot completely. Exactly. This is one of the problems this JEP attempts to solve. > separate everything that isn't "main-related" into its own class ... and then keep a nice clean public class called "Main" which contains 'only' the main method. Then you get to explain nicely how public classes have their own files, and if you attempt to run this class from the terminal, java will look for the 'main' function, and how this therefore needs to be public, static because you're running it straight from the class, void because you don't depend on it returning a value Only then you've taught a number of programming-in-the-large concepts as well as a bunch of Java technicalities -- all designed for the purpose of building large programs in a team -- before teaching what a computer program is. However, if you use this feature to teach your students and encounter a problem, we would be interested to hear your experience on the amber-dev mailing list.
- yyyk 4y agoThat's basically C# top-level programs[0]. IMHO, In C# these are a mixed bag, because once a project becomes more complex a file without a class looks out of place, so it's a feature for beginners/very simple programs. It was controversial enough that VS eventually included an option to create projects without using this... From the questioning around "needs to import basic utility classes", I'm guessing the feature following this would be something like C# implicit usings? [0] https://devblogs.microsoft.com/dotnet/c-9-0-on-the-record/#top-level-programs https://devblogs.microsoft.com/dotnet/c-9-0-on-the-record/#t... IIRC C# doesn't have the complex main selection as in here because it relies on csproj files.
- pjmlp 4y agoWorking with both stacks, I really hope Java doesn't start going through the C# trends of fighting Python and JS on lines of code to produce an "Hello World" application. Next step, language changes for Jakarta EE/Spring/Quarkus/Helidon minimal APIs.
- yyyk 4y agoWell, ASP.NET (Core) was startup was not exactly intuitive. How many people could type it up without a template? Routing was also way more complex than necessary...
- kaba0 4y agoIf you have an anonymous class, it can’t be referenced from elsewhere (it has no defined class name) so it is strictly only for small projects, which is imo the correct choice. But it is easy to “name” it when the program have to grow.
- bhawks 4y agoNow students will need to learn the pain of versioning on their first day of class. Bob: I get this weird error when I run this example from class. Sally: Works for me! Hey can you try running this? Bob: oh that works, lots of extra stuff in it. I guess I have to copy all of these things along for an app to work anywhere. Sally: I guess so - it's weird the simple example works on my laptop and not yours. Bob: must be a compiler bug, I hear about those alot in the compsci lab. Personally I think that the compiler should generate a synthetic main entry point when it encounters code that matches the new "launch protocol". It provides a degree of portability and repeatability over relying on the runtime to select the entry point. There are probably downsides here too.
- kaba0 4y agoHow many classes do you have that have a function named “main”?
- bhawks 4y agoApproximately none. Which is why I would be fine with javac generating a synthetic public static void main(string[] args) that forwards to it when the pattern is encountered. In this setup the generated classes/jars work fine without extra flags to java and even work on older jvm installations if you pass the right flags to javac at build time. I really struggle to come up with a reason to implement this as a change to java vm over just javac.
- kaba0 4y agoI really like this feature as they managed to cut down on verbosity with only a tiny amount of change to the language, the bigger part is done by simply changing the default classloader (it accepting not only public static void main(String… args))
- teo_zero 4y agoC is already much better, but we still have some boilerplate. Currently this is the bare minimum: #include <stdio.h> int main() { printf("Hello world\n"); return 0; } But I wish we could get rid of that "boilerplate" #include. I think compilers could add it by themselves when needed (many already suggest it to you if you forget it, so they do know when it's the case). On the other hand I wouldn't get rid of the explicit return from main(), as it has an important pedagogical function.
- JohnTordur 4y agoI disagree, #include <stdio.h> implies a system which has a stdout or stdin. That is not necessarily a case for embedded systems, where maybe at most you can blink an LED as a form of user output.
- teo_zero 4y agoI don't disagree, but the compiler could insert it automatically when you need it. In those rare cases where e.g. you want to use a function called printf() that's not the standard printf(), you explicitly opt out of the default via a compiler argument, a #pragma, etc.
- sgt 4y agoHow about a Main.java file that just contains the body of main() E.g println("Hello"); Without even the System.out Will allows for easy experimentation. Once you need to use methods, put it into a static method and a class.
- ajkjk 4y agoThis is easily 20 years overdue. It was obviously a major problem in the 2000s. It's not even about pedagogy -- the lack of ceremony for simple calculations is one of the reasons I reach for Python or even Typescript before Java to do one-off experiments, programming puzzles, or anything else.