日期:2014-05-20  浏览次数:20699 次

求解,主方法中也能创建对象??
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);这句也不需要了!