Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8019620

Support for default values in constructor/method parameters

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Fixed
    • Icon: P4 P4
    • None
    • 7, 8
    • specification

      A DESCRIPTION OF THE REQUEST :
      Hello all.
      I have a feature ask for Java.

      Please add support for the default values in constructor/method parameters.

      Something like this:

      class MyClass {
        MyClass(int param1 = 0, String param2 = " Java " , boolean param3 = false) {
          ...
        }
      }

      So all the following usages would be valid:

      new MyClass(100, " Java is cool " ,true);
      new MyClass(100, " Java is cool " );
      new MyClass(100);
      new MyClass();

      I have downloaded the most recent version of JDK, and this example gives me a compile error. So I have to write 3 or 4 versions of the constructor with different signatures. This makes code hard to understand.

      I have switched to Java after PHP, and it's very annoying that such a nice language still lacks this very efficient and useful feature.

      Thanks,
      W

      JUSTIFICATION :
      I googled for possible workarounds, but there seems to be no decent solution so far. People suggest one of the following:

      1) Writing all the variations of the same methods/constructors manually, which is exactly what I'm trying to avoid.

      2) Using factory methods to construct objects. This leads to overbloated code, and doubles the number of classes. Besides, this " helps " only with constructors, but not with regular method calls.

      3) Usign " virtual parameter " lists like new Something().withParam( " param1 " ,100).withParam(...) etc and passing it to constructor/method. This is also an obvious overkill, and it takes away the compiler type checking.

      So, this feature is really necessary.


      CUSTOMER SUBMITTED WORKAROUND :
      I know no decent workarounds.

      If any help with fixing this is appreciated, I can suggest a very easy way that will introduce the needed feature to Java. It does not require any changes in bytecode, fully compatible with existing code, and shows helpful compile error messages in the case programmer screws something.

      Regards,
      W

            abuckley Alex Buckley
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: