覆盖方法的规则

(1)覆盖方法的返回类型、方法名称、参数列表必须与它所覆盖的方法的相同。
(2)覆盖方法不能比它所覆盖的方法访问性差(即访问权限不允许缩小)。
(3)覆盖方法不能比它所覆盖的方法抛出更多的异常。——范围不能扩大(如父类方法throws FileNotFoundException,子类的覆盖方法不能throws FileNotFoundException, InterruptedIOException 或 throws Exception)但如果扩大的异常不是Java强制要求处理的,则可以,如:throws FileNotFoundException, NumberFormatException

Class A:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class A {
    public FileOutputStream aa() throws FileNotFoundException{
        FileOutputStream fout = new FileOutputStream("d:\\a.txt");
        return fout;
    }
}

Class B:

import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class B extends A{


    //覆盖方法:方法名和参数列表必须和父类的一致,,,返回类型也必须和父类的一致。
    /* 错, 原因:这是覆盖方法,因此返回类型必须和父类相同
        public void aa(){
        }
    */


    //※※子类覆盖方法的约束: 前不能小,后不能大

    /*
     * 错, 原因:覆盖方法中,子类方法的权限不能低于父类的

    FileOutputStream aa() throws FileNotFoundException{
        return null;
    }
    */

    /*
     * 错, 原因:覆盖方法中,子类方法抛出的异常不能比父类大。 本例中IOException是FileNotFoundException的父类,而父类的范围更广
    public FileOutputStream aa() throws IOException{
        return null;
    }
    */

    /*错, 原因:覆盖方法中,子类方法抛出的异常不能比父类大(更多也是更大)
    public FileOutputStream aa() throws FileNotFoundException,EOFException{
        return null;
    }
    */

    /*对,原因:虽然该覆盖方法比父类多抛出了一个NumberFormatException异常,
     * 但后者属于RuntimeException的子类。而运行时异常在编译阶段是不要求强制捕捉的!
    public FileOutputStream aa() throws FileNotFoundException,NumberFormatException{
        return null;
    }
    */

    /*对,子类覆盖方法的异常可以比父类更小,甚至可以不抛出异常!
    public FileOutputStream aa(){
        return null;
    }
    */


}

猜你喜欢

转载自blog.csdn.net/qq_38431927/article/details/77850756
今日推荐