3

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?

Mandar Pandit
  • 2,003
  • 5
  • 31
  • 49
user3743473
  • 45
  • 1
  • 5

4 Answers4

3

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!

Am_I_Helpful
  • 17,636
  • 7
  • 44
  • 68
3

Here's an analogy. You have a class Point:

public class Point {
    int x, y;

    private Point() {}

    public static Point getOrigin() {
        return new Point();
    }
}

It has a static method getOrigin() which returns a new Point object. This expression is similar to your InetAddress example:

Point p = Point.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.)

helderdarocha
  • 21,189
  • 4
  • 39
  • 58
2

java.net.InetAddress is a core java class that used for define address in the networks. This class has more static methods for simplify some common operations. These static method are designed base on Factory Method Pattern. For more information you can read Factory Method Pattern in wikipedia: http://en.wikipedia.org/wiki/Factory_(object-oriented_programming)

Vahid
  • 137
  • 8
0

This class represents an Internet Protocol (IP) address. An instance of an InetAddress consists of an IP address and possibly its corresponding host name

Static Methods are used as we have predefined process to be executed over network when any host-name or Address are referred..

for More Information and Method details please visit

http://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html

Jay Trivedi
  • 444
  • 4
  • 15