一道选择题:
A.方法覆盖要求覆盖和被覆盖的方法有相同的名字,参数列以及返回值
B.方法覆盖要求覆盖和被覆盖的方法必须具有相同的访问权限
C.覆盖的方法不能比被覆盖的方法抛出更多的异常
D.覆盖的方法一定不能是private的
ACD正确,B不正确。
就记录下BC的原因。
访问权限只能越来越松。例如代码:
public class MM {
protected void aaa() throws IOException{
throw new IOException();
}
}
public class T extends MM{
@Override
public void aaa() throws IOException,FileNotFoundException {
super.aaa();
}
}
如上,父类protected,子类public,可以,但反过来就不行了。
C选项。
子类中的覆盖方法只能抛出和基类方法相同或者更少的异常
就算你在子类写了覆盖多一个异常,但也无法捕捉到。
public class MM {
public void aaa() throws IOException{
throw new IOException();
}
}
public class T extends MM{
@Override
public void aaa() throws IOException,FileNotFoundException {
super.aaa();
throw new FileNotFoundException();
}
public static void main(String[] args) {
MM m = new T();
try {
m.aaa();
} catch (IOException e) {
System.out.println("xxx");
}
}
}
在子类中,无法捕获
FileNotFoundException。
package easy;
import java.io.CharConversionException;
import java.io.FileNotFoundException;
import java.io.IOException;
class MM {
public void aaa() throws CharConversionException{
throw new CharConversionException();
}
}
public class T extends MM{
@Override
public void aaa() throws CharConversionException,FileNotFoundException {
super.aaa();
throw new FileNotFoundException();
}
public static void main(String[] args) {
MM m = new T();
try {
m.aaa();
} catch (IOException e) {
System.out.println("xxx");
}
}
}
这样子类会报错,不能再抛出filenotfoundexception