为什么InetAddress类不能new初始化但可以定义对象:The constructor InetAddress() is not visible
2014-07-13 15:47
316 查看
InetAddress是java.net包里的一个类,在学习net包前建议先快速恶补一下《TCP/IP详解 卷1:协议》(一周看完理解80%即可);回到正题,如下语句会报错:
InetAddress ia = new InetAddress(); //报错:The constructor InetAddress() is not visible!
网上有一些错误的回答,要弄明白原因,须先查看java.net.InetAddress类的source code:
从源代码可以看出:类InetAddress和它的静态方法InetAddress.getByName(...)的作用域是public,因此可以在所有java类中引用,但其唯一无参构造方法的作用域是默认(空),默认的作用域限定该构造方法只能被java.net包里的类引用,因此在java.net包外定义的类使用new
InetAddress()会报错:构造方法不可见!解决方法是使用InetAddress.getByName(...)和InetAddress.getByAddress(...)等其他public方法,不详述,详细请查API;
InetAddress ia = new InetAddress(); //报错:The constructor InetAddress() is not visible!
网上有一些错误的回答,要弄明白原因,须先查看java.net.InetAddress类的source code:
public class InetAddress implements java.io.Serializable { //类InetAddress的作用域是public; ...... InetAddress() { //构造方法InetAddress()的作用域是默认(空); holder = new InetAddressHolder(); } ...... public static InetAddress getByName(String host) throws UnknownHostException { //静态方法getByName(...)的作用域是public; return InetAddress.getAllByName(host)[0]; } ...... }</span>
从源代码可以看出:类InetAddress和它的静态方法InetAddress.getByName(...)的作用域是public,因此可以在所有java类中引用,但其唯一无参构造方法的作用域是默认(空),默认的作用域限定该构造方法只能被java.net包里的类引用,因此在java.net包外定义的类使用new
InetAddress()会报错:构造方法不可见!解决方法是使用InetAddress.getByName(...)和InetAddress.getByAddress(...)等其他public方法,不详述,详细请查API;
相关文章推荐
- The constructor SearchParam() is not visible
- 为什么C++中的类不能定义自身类的对象,而java可以
- 为什么C++中的类不能定义自身类的对象,而java可以? 【转载】
- The constructor Vibrator() is not visible
- web工程下的有些路径的jsp可以直接在http url中输入进行显示,有些却不能显示??The requested resource is not available.
- 对象的当前状态使该操作无效 or SPListItem Update Operation is not valid due to the current state of the object
- the Project type is not supported by installation 项目类型不能正确加载
- The constructor someMethod() is not accessible due to restriction on required library
- intel 的千兆网卡出现 The EEPROM Checksum Is Not Valid,不能用,解决的办法!
- android 3des加密Access restriction: The constructor SunJCE() is not accessible due to restrictio
- GeoDatabase元数据不能编辑的问题“The application is not licensed to perform this operation ”
- InetAddress为什么不能new而可以直接拿来用
- IIS不能用,报错:Failed to execute request because the App-Domain could not be created. Error: 0×80070005 Access is denied
- SPListItem Update Operation is not valid due to the current state of the object(对象的当前状态使该操作无效。)
- The method * from the type * is not visible
- 定义一个单例模式的类,在这个类中,只有唯一的实例,不能new出来其他的实例对象。
- the Project type is not supported by installation 项目类型不能正确加载
- 对自定义函数建立索引时抛异常--ORA-30553: 函数不能确定(ORA-30553: The function is not deterministic)解决方法
- Access restriction: The constructor SunJCE() is not accessible due to restriction on required library E:/JDK/JDK1.6.0_03/jdk1.6.
- Access restriction: The constructor SunJCE() is not accessible due to restriction on required librar