Why am I getting an error: illegal start of expression public voidm1() { (in a short code)

Why am I getting an error: illegal start of expression public voidm1() { (in a short code)

给定: 考虑以下接口和 class: class C 的代码必须满足哪些条件才能成功编译?

这是老师给我们的代码片段


    public interface I {
    public void m1();
    public void m2();
    }


    public class C implements I {
      // code for class C
    }

这是一个非常模糊的问题。到目前为止,这是我尝试过的方法,但我得到了 illegal start of expression public void m1(){

到目前为止的代码:

     interface I {
    public void m1();
    public void m2();
}

public class C implements I {
    public static void main(String[] args){
        public void m1() {
            System.out.println("To be honest..");
        }
        public void m2() {
            System.out.println("It's a vague question to begin with.");
    }
}

class Main {
    public static void main(String[] args) {
    C why = new C();  
    why.m1();
    why.m2();
    }
}

如何修复错误?其实我也不知道怎么安排好..

(现在已经解决了,谢谢,非常感谢)

禁止嵌套方法定义

您不能在另一个命名方法的定义中定义一个命名方法。

所以这个:

    public static void main(String[] args){
        public void m1() { …

…是非法的。

你的main方法是一种方法——一种非常特殊的方法,但仍然是一种方法。因此,将您的 m1 方法移到其他地方。

package work.basil.demo;

// This class carries 3 methods, 1 special `main` method, and 2 regular methods.
public class C implements I
{
    public static void main ( String[] args )
    {
        System.out.println( "Do stuff here… instantiate objects, call methods. But do not define a nested method." );
        C see = new C();
        see.m1();
        see.m2();
    }

    public void m1 ( )
    {
        System.out.println( "Running m1 method." );
    }

    public void m2 ( )
    {
        System.out.println( "Running m2 method." );
    }
}

当运行.

Do stuff here… instantiate objects, call methods. But do not define a nested method.
Running m1 method.