InetAddress为什么不能new而可以直接拿来用

        InetAddress类是一个表示互联网协议(IP)地址的类,但是如果按照以往:InetAddress ia = new InetAddress();却发现提示"The constructor InetAddress() is not visible"构造函数不可见的错误。也就是说这个类不能new。为什么呢?

        但是如果直接把这个类拿来调用其方法,却可以。查看该类源码,该类不是静态类,但是其有静态方法,因为静态方法可以直接通过命名空间调用,如:

InetAddress s = InetAddress.getByName("www.baidu.com");


        如果要调用该类的非静态方法,须先生成一个类(即调用其中的静态方法,返回一个InetAddress类),如:

package javaday.socket;

import java.io.IOException;
import java.net.InetAddress;

public class EchoSocket {
    public static void main(String[] args) throws IOException {
        InetAddress ia = InetAddress.getByName("www.baidu.com");
        System.out.println(ia.getHostAddress());
    }

}
原文地址:https://www.cnblogs.com/thinksasa/p/2782348.html