我正在尝试使用DrJava学习Java。
当我尝试运行这段代码时,DrJava告诉我:
静态错误:此类没有接受String []的静态void main方法。
我不能得到的是为什么DrJava告诉我没有主要原因。这是班级犬类宣言后的第一行;而且我没有看到任何拼写错误或丢失标点符号。
我尝试使用谷歌搜索,但我不明白they were talking about。
如果有人能够以一种实际上没有给我答案的方式告诉我,那将会很好,但是让我自己弄清楚为什么会发生这种情况 - 但如果问题也是如此基本创造学习机会,然后我会采取解决方案;我猜。
/*
* This is an exercise designed to practice creating a class Animal
* And then creating another class canine in which to create an object dog.
* The reason I want to call from one class to another is because I want
* to understand how classes, objects, inheritance, etc. works.
* Clearly, class canine is -in my mind at least, a child of class Animal.
* The main method of canine then calls method attributes I think are being
* inherited by dog and wolf,from the class Animal.
*/
public class Animal {
void growl() {
System.out.println("Grrr");
}
void bark() {
System.out.println("Arf! Arf!");
}
}
class canine {
public static void main(String[]args) {
Animal dog = new Animal();
dog.bark();
Animal wolf = new Animal();
wolf.growl();
}
}
答案 0 :(得分:3)
该代码与java
命令行工具java canine
执行java canine
后,您将告诉java
工具查找并加载canine
类并运行其main
方法。
如果您使用的是java Animal
,则问题是Animal
没有main
。 canine
确实如此。
显然,至少在我的脑海里,班级犬是动物类的孩子
不,canine
与Animal
之间没有任何关系,canine
使用Animal
中的main
除外。例如,canine
取决于Animal
,但与其无关。如果你想让它成为一个子类(一个相当合理的解释"子类"),你可以在它的声明中添加extends Animal
。如果您希望它是nested class(另一个相当合理的解释"子类"),您可以将放在 Animal
中。
来自你的评论:
但我仍然不明白为什么DrJava告诉我它没有静态的void main方法接受String []。另外,当我在DrJava上运行时,它没有打印任何东西。
我希望您通过将canine
放在与Animal
相同的文件中,使Animal
公开,然后期望DrJava确定它应该运行{而混淆DrJava {1}}而不是canine.main
。请参阅以下有关最佳做法的说明。
来自另一条评论:
但是没有
Animal.main
直接调用dog.bark()
中的函数?为什么我需要"扩展"在这种情况下?
你不是。一个类可以使用另一个类,而它们之间没有任何继承关系,就像你的代码一样。这是你使用术语" child class"在建议您意图继承或类似的评论中。
旁注:虽然您不必遵循它们,但遵循标准Java命名约定是一种很好的做法。类名应该是最初的上限和CamelCase。所以Animal
而不是Canine
。
附注2:作为Hovercraft Full Of Eels says,最好将每个类放在自己的canine
文件中,该文件以类的名称命名。从技术上讲,您可以将非公开类放在任何.java
文件中(这就是为什么该代码与.java
中的canine
一起使用),但一般来说,最佳做法是将它们分开。因此,您Animal.java
包含Animal.java
类,Animal
包含canine.java
类(或更好,canine
包含Canine.java
} class)。