卡雷尔如何在没有“主要”方法的情况下运行?
我想在像Karel这样的程序中机器人运行,因为它没有使用main()方法。 相反,它使用了run()方法:
import stanford.karel.Karel; public class CollectNewspaperKarel extends Karel { public void run() { move(); } }
它是如何工作的?
实际的主要方法是在其他地方。 例如,在KarelRunner类中 。 当java执行程序时,它实际上是在run类中执行main方法。 从该转轮代码调用您自己的run方法。
“main”方法是每个java程序的起点。 这个类的内容是它本身不是一个java程序,是在某种类型的框架内执行的(在这种情况下是karel机器人java实现),这个框架当然有一个“主”方法但不是这个类, framework知道如何加载这个类并执行他的run方法。
这个“程序”是设计用于执行特定类型程序的框架,我不知道这个“karel框架”,但是例如,当你编写一个java web应用程序时,你编写了一个“servlet”,但是你没有写一个“主要”方法。 有一些称为“应用程序服务器”的程序当然有一个“主”方法,并采用这个servlet类并执行以响应某些http消息。
它没什么奇怪的。 CollectNewspaperKarel
类只是扩展了Karel的行为。 它不需要main
方法。
作为程序入口点的类需要有一个main
方法并创建一个CollectNewspaperKarel
实例,如:
public class MyProgram { public static void main(String[] args) { CollectNewspaperKarel cnpk = new CollectNewspaperKarel(); cnpk.run(); } }
或者CollectNewspaperKarel的实例可以是静态字段:
public class MyProgram { private static CollectNewspaperKarel cnpk = new CollectNewspaperKarel(); public static void main(String[] args) { cnpk.run(); } }
Karel不是一个应用程序,它是一个API。 你做了申请。
当您阅读所有这些说明时,您会发现Karel运行的程序只是较大系统的一小部分 – 较大的系统涉及绘制地图,发现逻辑错误等。您在run()
编写内容,然后你使用其中一个实际运行整个系统的类,并在你的程序中使用一个THOSE调用run()
。 祝你好运。
关键是非常简单: extends Karel
Karel
类是实现Runnable
,并且其中有很多方法。
它没有试图详细说明它所做的一切,它看起来像这样:
public class Karel implements java.lang.Runnable { private static final int NORTH = 0; private static final int EAST = 1; private static final int SOUTH = 2; private static final int WEST = 3; private static final int INFINITE = 99999999; private stanford.karel.KarelWorld world; private int x; private int y; private int dir; private int beepers; public Karel() { /* compiled code */ } public void run() { /* compiled code */ } public void move() { /* compiled code */ } public void turnLeft() { /* compiled code */ } public boolean beepersPresent() { /* compiled code */ } public boolean noBeepersPresent() { /* compiled code */ } public boolean beepersInBag() { /* compiled code */ } public boolean noBeepersInBag() { /* compiled code */ } public boolean facingNorth() { /* compiled code */ } public boolean facingEast() { /* compiled code */ } public boolean facingSouth() { /* compiled code */ } public boolean facingWest() { /* compiled code */ } public static void main(java.lang.String[] args) { /* compiled code */ } protected void start() { /* compiled code */ } protected void start(java.lang.String[] args) { /* compiled code */ } ... }
我从那里拿出了很多方法,因为它定义了很多东西。
但是我留在那里的矿石…… protected void start(java.lang.String[] args)
(至少,这就是我的图书馆检查员如何解释它)。 深入研究这段代码,看来这会调用KarelProgram中的main()
,但在大多数情况下,这既不是在这里也不是在那里。
因此你有inheritance权。 您正在inheritance代码正在使用的许多其他方法。 你正在使用move();
在该代码中,但没有定义它应该没有比定义main(java.lang.String[] args)
更令人惊讶。
只需在IDE中打开jar中的类即可。