类A
class A{
protected int method(int a,int b){return 0;}
}
which two vaild in a class that extends class A?(choose two)public int method(int a,int b){
return 0;
}
private int method(int a,int b){
return 0;
}
private int method(int a,long b){
return 0;
}
public short method(int a,int b){
return 0;
}
static protected int method(int a,int b){
return 0;
}
class A{
protected int method(int a,int b){return 0;}
}
which two vaild in a class that extends class A?(choose two)public int method(int a,int b){
return 0;
}
private int method(int a,int b){
return 0;
}
private int method(int a,long b){
return 0;
}
public short method(int a,int b){
return 0;
}
static protected int method(int a,int b){
return 0;
}
//访问限制不能比protected窄
public int method(int a,int b){
return 0;
}
//这个不是覆盖,重载了method方法,可以。
private int method(int a,long b){
return 0;
}
return 0;
} static protected int method(int a,int b){
return 0;
}覆盖:public int method(int a,int b){
return 0;
} private的访问权限最低不能覆盖比他权限高的方法
private int method(int a,int b){
return 0;
}
覆盖 父类的方法不能用 static 修饰.
public class TestMethod {
public TestMethod(){
System.out.println("无参数构造方法");
}
private TestMethod(int i){
System.out.println("整形参数="+i);
}
protected TestMethod(String s){
System.out.println("字符串参数="+s);
}
public static void main(String args[]){
new TestMethod();
new TestMethod(23);
new TestMethod("abcdef");
}
}运行这些代码你就知道了
return 0;
}
这个为什么不对??
首先你的题目是
which two vaild in a class that extends class A?(choose two)
它的意思是下面中有哪两个方法是在一个类中是继承自A的。也就是说下面的这些方法是在一个继承了class A类的。例如
class B extends A
{}
而这里有两个概念需要我们弄清楚 “重载”,“覆盖”我们需要现搞清楚这几个的区别和相同点。
下面我们来一个个的看第一个:
public int method(int a,int b){
return 0; //覆盖
}
这个方法除了访问权限不同外其他都是一样的。并且扩大了访问权限所以它符合重写的定义。但是不能缩小访问权限。
第二个
private int method(int a,int b){
return 0; //错误的覆盖方法
}
这个方法也是访问权限的不同,但是它降低了访问权限所以是错误的重写方法。所以覆盖的方法当然不能是private第三个
private int method(int a,long b){
return 0; //重载
}
这里不仅改变了访问权限同时参数的类型也发生了改变。这里为什么是重载呢?首先覆盖是方法名和参数需要相同而且它的访问限制变成了private 就不符合覆盖方法了。第四个
public short method(int a,int b){
return 0; //既不是覆盖也不是重载
}
这个方法中只有返回类型的不同,所以当然不可能是方法的覆盖,那是不是重载呢?假设在同一个类中当然也不是重载因为它的参数的类型和参数的个数和个数都没有发生改变所以不是。而重载的返回类型和访问限制可以有不同。第五个
static protected int method(int a,int b){
return 0; //既不是覆盖也不是重载
},
这是一个静态的方法,因为是静态是不会发生覆盖的。静态方法是在编译的时候把静态方法和类的引用类型进行匹配。这里重载是发生在同一个类中的所以重载的方法在这里不能选。但是一看只有第一个符合,但是不要忘记第五个是静态的方法所以也符合条件。
所以这里选择第一个和第二个。这里不知道对不对,仅供参考,若有错误,请指出来。
因为方法名和参数列表唯一确定一个方法,覆盖的时候不能改变返回值,否则子类调用此方法时就会产生混乱:superObject.method(1, 2); <------- 父类调用返回int
subObject.method(1, 2); <------- 父类调用却返回short多态的时候,程序员不知道要用什么来接收method的返回值.