2.以下程序的运行结果是( ) class Person{ public Person(){ System.out.println(“this is a Person”); } } public class Teacher extends Person{ private String name=”tom”; public Teacher(){ System.out.println(“this is a teacher”); super(); } public static void main(String[] args){ Teacher teacher = new Teacher(); System.out.println(this.name); } }
时间: 2024-03-25 07:40:00 浏览: 83
该程序无法编译通过,因为在 `Teacher` 类的 `main()` 方法中,使用了关键字 `this` 来引用类成员变量 `name`,而 `this` 关键字只能在实例方法中使用,无法在静态方法中使用。因此会出现编译错误。
如果将 `System.out.println(this.name);` 修改为 `System.out.println(teacher.name);`,则程序运行结果为:
```
this is a Person
this is a teacher
tom
```
即首先输出 "this is a Person" 和 "this is a teacher",然后输出 `teacher` 对象中的 `name` 成员变量值 "tom"。
相关问题
class Person{ public Person(){ System.out.println(“this is a Person”); } }
这是一个简单的 Java 类 `Person`,包含一个无参构造方法。在该构造方法中,使用 `System.out.println()` 方法输出了一行文字 "this is a Person"。
该类可以被实例化,每次实例化时都会自动执行该构造方法,并输出 "this is a Person"。
可以通过以下代码实例化该类:
```
Person p = new Person(); // 输出 "this is a Person"
```
24.下面程序运行的结果是 public class Teacher extends Person { private String name = "tom"; public Teacher0f System.out.printin("This is a teacher.") super0;
程序会报错,因为 Teacher 类中的构造方法没有被定义。正确的代码应该是:
public class Teacher extends Person {
private String name = "tom";
public Teacher() {
System.out.println("This is a teacher.");
super();
}
}
这样就可以正确地输出"This is a teacher."了。