Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do the Inet*Address classes have no visible constructors?

Tags:

java

Why do the InetAddress, Inet4Address, and Inet6Address classes have no visible constructors?

like image 287
Sheo Avatar asked Dec 12 '11 05:12

Sheo


People also ask

What is Inet address class?

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.

What is Inet address explain with example?

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.

Which pattern do you use to create instances of Java Net InetAddress?

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.)

How do I create an InetAddress instance?

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.


1 Answers

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; or
  • getAllByName(), 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
like image 56
paxdiablo Avatar answered Nov 02 '22 23:11

paxdiablo