URLs are write-once objects using you (which just use URL objects). You cannot change them.
URL must be created and initialized internally, sometime, so someone needs to modify them. Optimally, this would have to be done in your constructor, but this would lose flexibility. URL can indicate a variation of objects, and an implementation for accessing and processing them is not limited to the standard library; you can write implementations for processing user protocols.
Btw, in Java 8 they are not protected , but private, but even more restrictive (but not so important, since the URL class is declared final anyway, so you cannot subclass it).
Edit: Example
The URL class has many constructors: some allow you to specify different parts of the URL, such as protocol, host, port, etc., and there are some that allow you to specify the URL as one String : spec .
In the latter case (if the URL is specified as one String ), various parts of the URL (protocol, host, port, etc.) must be parsed from String . This parsing is done using the URLStreamHandler , which when analyzing String in the implementation of URLStreamHandler.parseURL() must use the URL.set() method to set the different parts back to the URL class, because the fields containing these parts are private . and there are no installation methods for them.
Because parsing is done in another class ( URLStreamHandler ), the URL provides a non-public method for retrieving the result of the parsing. This provides flexibility as you can replace / extend the URLStreamHandler , but still allow the URL declare final and be "write-once".
source share