弄清Java中方法覆盖时的规则

来源:互联网 发布:淘宝纹身器材哪家好 编辑:程序博客网 时间:2024/05/29 04:09

今天浏览网页,无意间看到这样一道题:

class A{

  protected int method(int a){

     return 0;

  }

}

which two are valid in a class that extends A?

A:public int method(int a){return 0;}

B:private int method(int a){return 0;}

C:private int method(long a){return 0l;}

D:public short method(int a){return 0;}

E:static protected int method(int a){return 0;}

 

我用Eclipse敲了一遍,正确的是AE,但是C没有明确报错,只是一个警告,分析:

在对父类方法进行覆盖时,不能缩小父类方法的访问权限,因此A对B错

C实际上没有对A的method方法进行覆盖,应为他们的参数列表不同

D不能改变覆盖的方法的返回值,D错

E正确

 

原创粉丝点击