下列Java代码段中,存在编译错误的是哪一行? public class Student { String name; static String school; public void read() { System.out.println(school); } public static void setInfo() { name = "LiHua"; // 第9行 this.school = "PKU"; // 第10行 Student s = new Student(); s.read(); // 第12行 Student.getSchool(); // 第13行 } public static String getSchool() { return school; } }
答案解析
核心考点:static方法的访问限制、this关键字的使用限制。
解题思路分析:
1. 类方法(static方法)中不能直接访问实例变量/方法,也不能使用this
2. 第9行直接访问实例变量name,违反static方法规则
3. 第10行使用this.school,static方法中不能使用this
4. 第12行通过创建实例后调用实例方法,是合法访问
5. 第13行正确调用static方法
选项分析:
A. 正确:直接访问实例变量name,违反类方法规则
B. 错误:语法错误,但实际编译错误会早于第10行出现
C. 合法操作,无错误
D. 合法static方法调用,无错误
易错点:可能误选B,但第9行的编译错误会先被发现。关键依据:类方法中直接访问实例变量是首要错误。
正确答案:A