首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

求解,主步骤中也能创建对象?

2012-09-27 
求解,主方法中也能创建对象??public class ExceptionTest {public static void main(String args[]) {try

求解,主方法中也能创建对象??
public class ExceptionTest {

public static void main(String args[]) {
try {
new ExceptionTest().methodA(5);
} catch (IOException e) {
System.out.println("caught IOException");
} catch (Exception e) {
System.out.println("caught Exception");
} finally {
System.out.println("no Exception");
}
}

void methodA(int i) throws IOException {
if (i%2 != 0)
throw new IOException("methodA IOException");
}
}
为什么在try语句中可以这样写,new ExceptionTest(),主方法是个静态的方法?

[解决办法]
new ExceptionTest().methodA(5);

相当于 ExceptionTest ex = new ExceptionTest();/>*>>>*>>>*>*>>>**/ ex.methodA(5);

ex是我定义出来的对象(怎么定义都可以) 

写程序的作者把这句省略了,直接简单写成new ExceptionTest().methodA(5);

其实意思都一样,另一方面也能减少内存负担。

method(); 不是静态方法,所以类实例化对象,才能引用。

如果是静态方面,那么直接就可以写成method();

new ExceptionTest().methodA(5);这句也不需要了!

热点排行