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
}
}
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?