Search code examples
javagreenfoot

Inheritance related query regarding Greenfoot


For all of those who aren't familiar with Greenfoot, below is the context:-

Greenfoot is a java learning tool using some animation. In this tool, there is a predefined class called 'Actor' with some predefined methods. We can add objects by creating sub-classes of this class such as 'Car', 'Truck', etc.

I created sub-classes to 'Actor' called 'Car' and 'Truck'. I called the predefined method in 'Actor' class called 'move(some argument denoting speed of the movement)' from a method in the 'Car' class as: move(5);.

My question is this: Why I don't need to mention the 'Car' class object here as in: c1.move(5); where 'c1' is the 'Car' class object? I can understand that since I didn't defined the 'move' method in the 'Car' class, it will directly call and implement the predefined method in the 'Actor' class, but how it is able to know that I meant 'Car' class object here? It could have been 'Truck' class object too! Is it because I am calling the method from a 'Car' class method, it is inferring that?

If yes, then is this a general rule in java or only a specific implementation of Greenfoot?


Solution

  • Suppose in main(), you are creating an object of the Car class, and calling a method, say methodThatCallsMove():

    Car c = new Car();
    c.methodThatCallsMove();
    

    Inside this method, you are calling move(5) simply:

    methodThatCallsMove(){
      move(5);
    }
    

    This will automatically call the current object's (i.e. c) method move. The version of move() being bound to the object c here depends upon whether you have implemented a separate move() method in your Car class, or whether you are simply inheriting the original move() method in the Actor class. The former condition calls the move() implemented in your Car class, the latter will call the one in your Actor class.

    Hope this helps.