请修复简单Java代码中的错误

时间:2016-06-21 18:39:46

标签: java inheritance

我正在尝试使用Class E扩展Class Test1,我只想显示一条消息。

class Test1
{
 public static void main(String[] args) 
 {
    E e = new E();
 } 
} 
class E extends Test1
{
  System.out.println("Hello World!");
}

我收到这些错误:

Test1.java:10: <identifier> expected
        System.out.println("Hello World!");
                          ^
Test1.java:10: illegal start of type
        System.out.println("Hello World!");
                           ^
2 errors

1 个答案:

答案 0 :(得分:2)

您的E类缺少构造函数。

class Test1
{
 public static void main(String[] args) 
 {
    E e = new E();
 } 
} 
class E extends Test1
{
  public E(){
     System.out.println("Hello World!");
  }
}

E类应该有实例块

class Test1 {
    public static void main(String[] args) {
        E e = new E();
    } 
} 
class E extends Test1 {
  {
     System.out.println("Hello World!");
  }
}