Review Override by a SCJP Test Question

本文解析了一道SCJP考试中的题目,探讨了子类方法重写父类方法时抛出异常的不同情况及其对编译的影响,并通过示例说明了为何某些情况下程序能够成功编译。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Below is a SCJP test question:

8、What will happen when you compile this program?

public class Test{
    protected void start() throws ClassCastException{
        //body omitted
    }
}
 
class Child extends Test{
    public void start() throws Exception{
        //body omitted
    }
}
 
A. The program will compile successfully.
B. The program will not compile because the start() in the subclass throws a different exception than in the parent class.
C. The program will not compile because the start() in the subclass is public, whereas it is protected in the parent class.
D. The program will not compile because the start() in the subclass has different accessibility and throws a different exception than in the parent class.

Which one is correct maybe obviously.

Subclass’s method who override parent class’s method can not throw exceptions bigger than whose parent class does. So , absolutely , B is the correct answer.

But…How about this:

public class Main{
    private void execute() throws ClassCastException{
        System.out.println("execute in Main");
    }
}
 
class Child extends Main{
    protected void execute() throws Exception{
        System.out.println("execute in Child");
    }
}

The above program is similar. One of its method is trying to override parent class’s method.

However, while we try compile it and it works well. Oops, It is so funny.

Have a look at the parent class we can notice that the execute() method is private. The subclass Child’s execute() method can not override this method and they are irrelevant. This is the reason why we can compile the above program successfully .

---EOF---

HOW ABOUT TAKING A SCJP EXAMINATION?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值