首页 > 解决方案 > 为什么我得到一个错误:表达式 public voidm1() { 的非法开始(在一个短代码中)

问题描述

给定:考虑以下接口和类:为了使该代码成功编译,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();
    }
}

如何修复错误?我其实不知道如何正确安排它..

(现在已经解决了。谢谢。我真的很感激)

标签: javacompiler-errors

解决方案


禁止嵌套方法定义

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

所以这:

    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.

推荐阅读