请先看这一题:
Given:
public class SuperCalc{
protected static int multiply(int a, int b){return a * b;}
}
and:
public class SubCalc extends SuperCalc{
public static int multiply(int a, int b){
int c = super.multiply(a, b);
return c;
}
}
and:
SubCalc sc = new SubCalc();
System.out.println(sc.multiply(3, 4));
System.out.println(SubCalc.multiply(2, 2));
What is the result?
A. 12
4
B. The code runs with no output.
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 21.
E. Compilation fails because of an error in line 22.
F. Compilation fails because of an error in line 31.
答案:E
然后我测试下,果然显示编译错误!提示为:can't use super in a static context.
谁能从Java机制,给我解释一下这是为什么呢?
Given:
public class SuperCalc{
protected static int multiply(int a, int b){return a * b;}
}
and:
public class SubCalc extends SuperCalc{
public static int multiply(int a, int b){
int c = super.multiply(a, b);
return c;
}
}
and:
SubCalc sc = new SubCalc();
System.out.println(sc.multiply(3, 4));
System.out.println(SubCalc.multiply(2, 2));
What is the result?
A. 12
4
B. The code runs with no output.
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 21.
E. Compilation fails because of an error in line 22.
F. Compilation fails because of an error in line 31.
答案:E
然后我测试下,果然显示编译错误!提示为:can't use super in a static context.
谁能从Java机制,给我解释一下这是为什么呢?
int c = super.multiply(a, b);改为
int c = SuperCalc.multiply(a, b);
如果你理解this不能用在static的上下文,super也就理解了
can't use super in a static context.不能在静态环境使用super他不属于某个类