How does Karel run without “main” method?

前端 未结 5 1658
臣服心动
臣服心动 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:44

    The key to this is quite simple: extends Karel

    The Karel class is one that implements Runnable, and has quite a few methods within it.

    Without trying to go into detail about what all it does, it looks something like this:

    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 */ }
    
        ...
    }
    

    I took out quite a few methods from there because its a very long list of things it defines.

    But ore that last one that I left in there... protected void start(java.lang.String[] args) (or at least, that's how my library inspector interpreted it). Digging into this code, it appears that this invokes main() in KarelProgram, but for the most part, thats neither here nor there.

    And thus you have inheritance. You are inheriting a number of other methods that the code is using. That you are using move(); in that code but not defining it should be no more surprising than having a main(java.lang.String[] args) defined.

    All it takes is opening up the class in the jar in your IDE.

提交回复
热议问题