为什么会出现错误:表达式public voidm1(){的非法开始(在短代码中)

krugob8w  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(322)

给定:考虑以下接口和类:类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();
    }
}

如何修复错误?我真的不知道怎么安排好。。
(这个问题现在已经解决了。谢谢您。我真的很感激)

qojgxg4l

qojgxg4l1#

禁止嵌套方法定义

不能在另一个命名方法的定义中定义一个命名方法。
因此:

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.

相关问题