JDK-8282880 : java.net.InetAddress should be a sealed class
  • Type: CSR
  • Component: core-libs
  • Sub-Component: java.net
  • Priority: P3
  • Status: Closed
  • Resolution: Approved
  • Fix Versions: 19
  • Submitted: 2022-03-09
  • Updated: 2022-03-12
  • Resolved: 2022-03-12
Related Reports
CSR :  
Description
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 {
```


Comments
Moving to Approved.
12-03-2022