又是一道继承题

Sodino 2008-12-06 05:08:18
Question 73
Given:
11. static classA
{
12. void process() throws Exception { throw new Exception(); }
13. }
14. static class B extends A {
15. void process() { System.out.println("B ")} //问题一:为什么在这儿不出错,我是这样想的:A类中process方法有throws Exception,所以继承类中应该与被继承保持一致,也就是应该加上throws Exception才对啊。所以答案我选了D。
16. }
17. public static void main(String[] args) {
18.A a=new B();
19. a.process();
20.}
What is the result?
A. B
B. The code runs with no output.
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 15.
E. Compilation fails because of an error in line 18.
F. Compilation fails because of an error in line 19.
Answer: F

问题二:我在eclipse中输入题目中的代码进行测试时,刚输入 static class A{},就被提示:Illegal modifier for the class A; only public, abstract & final are permitted,是题目本来就有错吗?
...全文
94 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wenjjing2lianee 2008-12-06
  • 打赏
  • 举报
回复

//就算你这样写也是同样的地方出现异常:
public class Test {
static class A
{
void process() throws Exception
{
throw new Exception();
}
}
static class B extends A
{
void process() throws Exception
{
System.out.println("B ");
}
}
public static void main(String[] args) {
A a=new B();
a.process();
}

}


//解决方法是在a.process()抛出异常,主要因为异常没处理的原因
public class Test {
static class A
{
void process() throws Exception
{
throw new Exception();
}
}
static class B extends A
{
void process()
{
System.out.println("B ");
}
}
public static void main(String[] args) {
A a=new B();
try {
a.process();
} catch (Exception e) {
e.printStackTrace();
}
}

}


tiyuzhongxin789 2008-12-06
  • 打赏
  • 举报
回复
的确是第19行出错,错误的确正如楼主所说B的process方法没有throws Exception,但这个编译方法本身的时候没问题,下面main里面调用的时候才出现问题
jhr924 2008-12-06
  • 打赏
  • 举报
回复
有意思, 还要继承throws Exception, 没遇见过
Lem丶 2008-12-06
  • 打赏
  • 举报
回复
恩恩,楼上说的很对
bigbro001 2008-12-06
  • 打赏
  • 举报
回复

public class Test
{
static class A
{
void process() throws Exception
{
throw new Exception();
}
}
static class B extends A
{
void process()
{
System.out.println("B ");
}
}
public static void main(String[] args) {
A a=new B();
a.process();
}
}



的确是第19行出错,错误的确正如楼主所说B的process方法没有throws Exception,但这个编译方法本身的时候没问题,下面main里面调用的时候才出现问题
1 error found:
File: C:\Documents and Settings\Administrator\Desktop\Test.java [line: 19]
Error: C:\Documents and Settings\Administrator\Desktop\Test.java:19: unreported exception java.lang.Exception; must be caught or declared to be thrown

62,614

社区成员

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

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