Instance main method and vararg constructor

Brian Goetz brian.goetz at oracle.com
Fri Jul 5 15:14:34 UTC 2024


It is reasonable to infer the semantics of a no-arg constructor as “give me a default-configured instance of this class”, where default-configured is controlled by the class.  This is done by Javabeans, serialization, test frameworks, and other frameworks.  But once a constructor has arguments, those arguments have semantics.  Can we really assume that a `String…` constructor is intended to be used with command-line-argument strings?  That seems more of a leap.

We do so with `main` because by longstanding convention, `main` functions/methods (going back to C) have been associated with the interface from the OS launcher to the program.  But I think that’s as far as we should take it?

> On Jul 5, 2024, at 11:05 AM, Tagir Valeev <amaembo at gmail.com> wrote:
> 
> Hello!
> 
> I wonder if we should enable instance main method if the class has only vararg constructor:
> 
> class Test {
>   Test(String... data) {
>   }
> 
>   void main() {
>     System.out.println("Hello World!");
>   }
> }
> 
> Java 22 doesn't like it:
> > \jdks\jdk-22\bin\java.exe --enable-preview Test.java
> error: can't find no argument constructor in class: Test
> 
> However, in other contexts, such a class is considered as a class that has no-arg constructor. E.g., we can subclass it without explicit super-constructor invocation:
> 
> class Test {
>   Test(String... data) {
>   }
> 
>   static class Use extends Test {}
> }
> 
> Would it be consistent to allow launching such classes?
> 
> With best regards,
> Tagir Valeev



More information about the amber-spec-experts mailing list