为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我的方法在主要方法中没有被检测到?

为什么我的方法在主要方法中没有被检测到?

慕码人2483693 2022-11-10 15:11:28
我只是在测试一些继承,但似乎我的方法没有被调用,甚至没有被 main 方法看到。它编译,但只是说文件中没有检测到方法。我的代码有什么问题?public class monkey{    public void main(String[] args){          Fruit jeff = new Fruit("ree");          Fruit mike = new Apple("ree");          jeff.talk();          mike.talk();    }class Fruit {     String sound;    public Fruit(String s) {       sound = s;    }     public void talk(){      System.out.print(sound);    }} class Apple extends Fruit {    public Apple(String s){      super(s);   }}}
查看完整描述

1 回答

?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

  • 将静态放在主要方法签名中。

  • 创建静态内部类,因为您想在静态 main 方法中访问这些类。

正确代码:

public class monkey {

    public static void main(String[] args) {

        Fruit jeff = new Fruit("ree");

        Fruit mike = new Apple("ree");


        jeff.talk();

        mike.talk();

    }


    static class  Fruit {

        String sound;


        public Fruit(String s) {

            sound = s;

        }


        public void talk() {

            System.out.print(sound);

        }

    }


    static class Apple extends Fruit {

        public Apple(String s) {

            super(s);

        }

    }

}


查看完整回答
反对 回复 2022-11-10
  • 1 回答
  • 0 关注
  • 59 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信