gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:55:28 24 4
gpt4 key购买 nike

我只是测试一些继承,但似乎我的方法没有被调用,甚至没有被主方法看到。它可以编译,但只是说文件中没有检测到方法。我的代码有什么问题吗?

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);
}
}
}

最佳答案

  • 将静态放入主方法签名中。
  • 创建静态内部类,因为您想在静态 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);
}
}
}

关于java - 为什么我的方法没有在主方法中被检测到?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56015863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com