求解,主方法中也能创建对象??

hbxf_xs 2012-09-07 08:33:20
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(),主方法是个静态的方法?
...全文
162 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
火光闪耀 2012-09-07
  • 打赏
  • 举报
回复
静态类是不用new的,可以直接类名.方法名使用。
  • 打赏
  • 举报
回复
肯定可以啦
wsyangzuda 2012-09-07
  • 打赏
  • 举报
回复
new ExceptionTest().methodA(5);

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

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

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

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

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

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

new ExceptionTest().methodA(5);这句也不需要了!
wang_liran 2012-09-07
  • 打赏
  • 举报
回复
实例化很正常嘛,主方法是静态方法
捏造的信仰 2012-09-07
  • 打赏
  • 举报
回复
楼主要学会贴代码:
public class A {
private String name;
}
guangmingguangming 2012-09-07
  • 打赏
  • 举报
回复
楼主为什么认为不可以呢,在main方法里new对象很正常呢。

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧