Thought on multiplicity of properties in Java

Martin Desruisseaux martin.desruisseaux at geomatys.com
Sat Sep 15 18:16:45 UTC 2018


I’m deriving Java interfaces from the UML of ISO 19111 international
standard, and a though come to my mind. This is not a request for
changing anything in the Java language now, I’m just wondering if this
is something worth to be considered for the future. This proposal would
require javac to handle Optional<Foo> and maybe Collection<Foo> method
return types in a special way, but would not require JVM change in my
understanding.

Sometime a property is optional in a parent class, but become mandatory
in some subclasses. In UML, the [0…1] multiplicity in parent class
become restricted to [1…1] multiplicity in subclasses. I wonder if javac
could do a special case for catching this model as below. Allow to override:

    class Parent {
        Optional<Foo> getFoo();
    }

with:

    class Child extends Parent {
        @MaybeSomeAnnotationMakingIntentClear
        @Override
        Foo getFoo();
    }

Those two methods differ only by the return type, which I think is
allowed at the JVM level. In the Child class, javac would generate the
following synthetic method:

    @Override
    final Optional<Foo> getFoo() {
        return Optional.of(getFoo());      // Invoke the getFoo() method that return Foo.
    }

Subclasses of Child can override only the method returning Foo, not
Optional<Foo>. In UML parlance, the [0…1] multiplicity can be restricted
to [1…1] but the converse is not allowed (this is the same reasoning
than method return type covariance in Java, applied to multiplicity
instead than type). Invocation of getFoo() on Parent class would invoke
the methods returning Optional<Foo>, while invocation of getFoo() on
Child class would invoke the method returning Foo. Whether the following
should be a compiler error or not is an open question:

    Child a = ...;
    Optional<Foo> foo = a.getFoo();

Something similar could be done for method returning Collection<Foo>
too, if we consider those methods as properties having a [0…∞]
multiplicity which can be restricted to [0…1] or [1…1] multiplicity in
subclasses. In summary, Java already has type covariance and I wonder if
it could be extended to "multiplicity covariance" with javac handling
Collection<Foo> as [0…∞], Optional<Foo> as [0…1] and Foo as [1…1]. I'm
of course not asking for any action; just curious if it is worth to put
on a list of possible future Java evolutions.

    Regards,

        Martin




More information about the core-libs-dev mailing list