java中方法覆盖的相关

一道选择题:

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






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值