java中,InetAddress为啥不能new对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java中,InetAddress为啥不能new对象相关的知识,希望对你有一定的参考价值。

为什么出现这个: java.net.InetAddress 中不是公共的;无法从外部软件包中对其进行访问

static InetAddress    getByAddress(byte[] addr)
//Returns an InetAddress object given the raw IP address .    
static InetAddress    getByAddress(String host, byte[] addr)
//Creates an InetAddress based on the provided host name and IP address.    
static InetAddress    getByName(String host)  
//Determines the IP address of a host, given the host's name.

这是因为java内部把InetAddress的构造函数私有化了,

private InetAddress()

这样,你就不能访问他的构造函数了,但是你可以通过InetAddress类里面的工厂方法来获得InetAddress对象,那些方法我写在上面。

新手一定会有疑惑,为什么不直接让我们用构造函数来实例对象,而用工厂方法,(工厂方法自己调用构造函数返回对象)下图所示。

static InetAddress    getByAddress(byte[] addr)

    return InetAddress(byte[] addr);

//这样返回自身对象的方法称为工厂方法。
//虽然构造函数是私有的,但是类内部的函数还是可以访问的。

这样岂不是很多此一举? 确实,表面上看,这样完全没有意义,但是实际上,你会发现,工厂方法相比构造函数的优点是工厂方法可以随意命名,但是构造函数不行。

有时候我们会通过方法的名字的不同来体现方法的不同意义,但是构造函数做不到这点,于是取而代之,用工厂方法,如上例getByAddress(byte[] addr)  getByName(String host) 很好的体现了一个用address构造,一个用name,但是构造函数永远做不到这点,所以这里使用工厂方法。

参考技术A 是不让new。但可以从下面的方法得到

static InetAddress[]
getAllByName(String host)
Given the name of a host, returns an array of its IP addresses,
based on the configured name service on the system.

static InetAddress
getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address .

static InetAddress
getByAddress(String host,
byte[] addr)
Create an InetAddress based on the provided host name and IP address
No name service is checked for the validity of the address.

static InetAddress
getByName(String host)
Determines the IP address of a host, given the host's name.追问

为什么不能new,还有哪些类也是这样

追答

至于为何,看API吧。

参考技术B 没有构造方法吧追问

那怎么调用非静态方法

追答

a757208523 的答案正解……

以上是关于java中,InetAddress为啥不能new对象的主要内容,如果未能解决你的问题,请参考以下文章

为啥我们不能像在 java 中那样使用 new ClassName() 而不是使用 new ClassName?

java里面为啥总要new,不new为啥不行?scanner scancer=new scan

为啥 InetAddress.getLocalHost().getHostName() 返回与 bash“主机名”不同的值?

java如何查询本机ip地址和mac地址

为啥我不能在 JavaScript/ES6 中使用带有箭头函数的`new`? [复制]

为啥 Java 隐藏他们的 getLocalHostName() 实现?