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

java.net.InetAddress should be a sealed class

XMLWordPrintable

    • Icon: CSR CSR
    • Resolution: Approved
    • Icon: P3 P3
    • 19
    • core-libs
    • None
    • minimal
    • Given that the `java.util.InetAddress` constructor is package-private, no sub-classes of this class are expected in any application code or non-JDK code.
    • Java API
    • SE

      Summary

      Mark java.net.InetAddress as a sealed class. Make java.net.Inet4Address and java.net.Inet6Address as the only permitted subclasses.

      Problem

      java.net.InetAddress is a public non-final class that only has package-private constructors. The only two sub-classes are the Inet4Address and the Inet6Address, both of which have only package-private constructors, and are final. Effectively, these are the only sub-classes of the java.net.InetAddress within the JDK. No other sub-classes are intended for the InetAddress.
      Therefore, marking it sealed allows the JDK code to take advantage of the compiler checks that will prevent any unexpected sub-classes to be introduced.

      Solution

      Mark the InetAddress class as sealed and permit only Inet4Address and Inet6Address classes to extended it. Both the Inet4Address and Inet6Address are final classes already.

      Specification

      --- a/src/java.base/share/classes/java/net/InetAddress.java
      +++ b/src/java.base/share/classes/java/net/InetAddress.java
      @@ -1,5 +1,5 @@
       /*
      - * Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved.
      + * Copyright (c) 1995, 2022, Oracle and/or its affiliates. All rights reserved.
        * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
        *
        * This code is free software; you can redistribute it and/or modify it
      @@ -223,7 +223,7 @@ import static java.net.spi.InetAddressResolver.LookupPolicy.IPV6_FIRST;
        * @see     java.net.InetAddress#getLocalHost()
        * @since 1.0
        */
      -public class InetAddress implements java.io.Serializable {
      +public sealed class InetAddress implements java.io.Serializable permits Inet4Address, Inet6Address {

            aefimov Aleksej Efimov
            dfuchs Daniel Fuchs
            Alan Bateman, Daniel Fuchs, Jaikiran Pai, Michael McMahon
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: