Q19
C 错误。在 main() 中只能直接调用静态方法或者访问静态域,而 this 和 super() 都是非静态的:
public class Test {
public static void main(String[] args) {
// Pass
System.out.println("Static field 'a' = " + a);
// Pass
foo();
// Error: this is a compilation error.
this.bar();
}
static void foo() {
System.out.println("Static method.");
}
void bar() {
System.out.println("Non static method.");
}
static int a = 10;
}
Q37
题目定义了两个 public class, 所以如果要完全模拟题目的情景,需要创建两个 .java 文件。因为每个 .java 文件里有且只能有一个 public clas.
// Parent.java
public class Parent {
public float aFun(float a, float b) throws IOException {
// ...
}
}
// Child.java
public class Child extends Parent {
// The following method definition will cause compilation error due to
// reducing the visibility of aFun(float, float)
float aFun(float a, float b) { }
}方法的可见性级别(访问权限)分为:
- public
- protected
- 默认级别,什么都不用写
- private
在 Java 中,子类继承父类时不能降低父类方法的可见性。
在此,Child 的 aFun 方法是默认级别的,可见性比 public 低,所以会造成编译错误(compilation error).
本文详细解析了Java中常见的编译错误案例,包括在main方法中非法使用this关键字调用非静态方法,以及子类方法可见性不当导致的错误。通过具体代码示例,帮助读者理解如何避免这些常见陷阱。
7869

被折叠的 条评论
为什么被折叠?



