Reputation: 11
Why we have not used new
keyword in the following program?
import java.net.InetAddress;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.pinterest.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}
Upvotes: 0
Views: 218
Reputation: 719436
Is
InetAddress
a static class?
Well, in a sense yes. All top-level classes are implicitly static ... in the sense that they don't require an instance of an outer class.
But you are not asking the right question. Static classes and static methods are different concepts ...
Why do we not use
new
key word with it?
Now ... the right question.
Because InetAddress.getByName(...)
is a static
method call that creates and returns an instance of Inet4Address
or Inet6Address
which are subtypes of InetAddress
.
Why did they do it this way? Why not just new
it?
InetAddress
objects are typically created by calling getByName
or a related method on a String
representing hostname or an array of bytes. This will give you either IPv4 or IPv6 addresses, or a mixture of both (with the getAll
methods). Since the true type of the result depends on the actual runtime arguments, it is not possible to do this with a constructor and new
.
There is another reason as well. In fact there is some caching going on under the covers. If the argument to (say) getByName
is a DNS name string, avoiding expensive DNS lookups is a good performance optimization. So results of lookups are cached, and a getByName
call can return an Inet4Address
or Inet6Address
that was created previously. You can't do that with a constructor and new
.
As @Turing85 notes, this is an example of the factory method design pattern.
Upvotes: 1
Reputation: 20195
Looking at documentation of InetAddress
, we see that this class does not provide public acessible constructors. It uses the factory method pattern instead.
Upvotes: 0