首页 > 试题广场 >

以下程序的输出结果为() class Demo{ publi

[单选题]
以下程序的输出结果为()
class Demo{
    public Demo(String s){
        System.out.print("hello");
    }
}
public class Test extends Demo{
    public Test (String s) {
        System.out.print("world");
    }
    public static void main(String[] args){
        new Test("hello world");
    }
}
  • world
  • hello
  • hello world
  • 编译错误
这个程序无法正常编译运行,因此没有输出结果。 原因分析: 在Java中,子类的构造方法在执行时会隐式调用父类的无参构造方法(即`super()`)。但在本题中: - 父类`Demo`只定义了一个带`String`参数的构造方法(`public Demo(String s)`),根据Java规则,此时编译器不会为`Demo`生成默认的无参构造方法。 - 子类`Test`的构造方法(`public Test(String s)`)没有显式调用父类的任何构造方法(如`super(s)`),因此编译器会尝试插入默认的`super()`来调用父类无参构造方法,但父类`Demo`不存在无参构造方法,导致编译报错。 综上,程序因编译错误无法运行,没有输出结果。
发表于 2025-08-08 19:49:43 回复(0)