java - 为什么我得到一个错误:表达式 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();
}
}
如何修复错误?我其实不知道如何正确安排它..
(现在已经解决了。谢谢。我真的很感激)
解决方案
禁止嵌套方法定义
您不能在另一个命名方法的定义中定义一个命名方法。
所以这:
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.
推荐阅读
- c# - DataTable.Select 将 DateTime 存储为字符串
- python - python中的'import ab as b'和'from a import b'有什么区别
- javascript - JS 代码在函数内部时的行为不同,并被调用
- javafx - 场景中的javafx按钮定位
- jenkins - jenkins build 没有触发 github push
- mysql - MySql - 无法添加外键约束
- typescript - 如何在 ionic 2 中禁用日期时间选择器中的特定日期列表?
- mysql - 多列 SQL 的 Case Then 语句
- hazelcast - Hazelcast 客户端配置中查询缓存的条目侦听器
- selenium - 未找到元素定位器