Why do the InetAddress
, Inet4Address
, and Inet6Address
classes have no visible constructors?
InetAddress class is Java's encapsulation of an IP address. It is used by most of the other networking classes, including Socket , ServerSocket , URL , DatagramSocket , DatagramPacket , and more. public final class InetAddress extends Object implements Serializable.
InetAddress class provides methods to get the IP of any host name for example www.javatpoint.com, www.google.com, www.facebook.com, etc. An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress represents the IP address with its corresponding host name.
getOrigin(); It's a very common pattern in many Java applications and APIs. It also allows you to control the instances that are created (the getOrigin() method could cache points and return a previously created one, it could always return the same object, etc.)
The InetAddress class doesn't have public constructors, so you create a new instance by using one of its factory methods: getByName(String host): creates an InetAddress object based on the provided hostname.
Because it's a factory class. Using static methods to return a factory instance makes sense when there are a small number of situations in which you will want to create such an object.
So, instead of overloading the constructor to the point where you'll have to remember all sorts of bizarre combinations of arguments to use for each given situation, it just gives you one (hopefully well-named) method per situation.
In this case, you can create an object with one of:
getLocalHost()
, getting your own address;getByName()
, getting the "primary" address for a site; orgetAllByName()
, getting a list of the addresses.This isn't an exhaustive list, see here for more of them, search that page for:
Methods in java.net that return InetAddress
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With