How does Karel run without “main” method?

前端 未结 5 1657
臣服心动
臣服心动 2021-01-21 20:34

I was wondering in the program like Karel the Robot runs because it does not used main() method. Instead it used run() method:

import stanford.karel.Karel;

publ         


        
5条回答
  •  广开言路
    2021-01-21 20:42

    There's nothing weird about it. The CollectNewspaperKarel class is just extending the behavior of Karel. It doesn't need to have a main method.

    The class that will be the entry point of the program does need to have a main method and create an instance of CollectNewspaperKarel, like:

    public class MyProgram {
    
        public static void main(String[] args) {
            CollectNewspaperKarel cnpk = new CollectNewspaperKarel();
            cnpk.run();
        }
    }
    

    Or the instance of CollectNewspaperKarel could be a static field:

    public class MyProgram {
        private static CollectNewspaperKarel cnpk = new CollectNewspaperKarel();
        public static void main(String[] args) {
            cnpk.run();
        }
    }
    

    Karel is not an application, it's an API. You make the application.

提交回复
热议问题