Search code examples
javainetaddress

INetAddress Direct Instantiation


I'm fairly new to Java but not programming and I ran into this:

InetAddress localAddress = InetAddress.getLocalHost();

It looked off to me. We're declaring localAddress as type InetAddress but it's being assigned an instance of a static method of InetAddress? Can anyone help me understand this?


Solution

  • The InetAddress class has no visible constructors.To create an InetAddress object,you have to use one of the available Factory Methods.

    Factory Methods are merely a convention whereby static methods in a class return an instance of that class.This is done in lieu of overloading a constructor with various parameter lists when having unique method names makes the results much clear!

    Three commonly used InetAddress factory methods are shown here :-

    static InetAddress getLocalHost() throws UnknownHostException
    static InetAddress getByName(String hostName) throws UnknownHostException
    static InetAddress[] getAllByName(String hostName) throws UnknownHostException
    
    // Contents taken from Java---The Complete Reference by Herbert Schildt...
    

    The getLocalHost() method simply returns the InetAddress object that represents the local host. Also you can instantiate using any of the three methods. I hope it clears your doubt!