why do we override/implement methods?

+1 R R · December 30, 2014
This is a more general Java question, but if you could give examples in Android that would help too.

I am having trouble understanding why we override/implement methods and what would happen if we don't? Like what is exactly going on here code wise? I understand what the 'extends' keyword does and how a class can be a subclass of another class but I really don't get what "overriding" really is or does.

I was looking for a good explanation on the Java Tutorials but couldn't really find one (maybe I missed it?). Any help/links to explanations would be greatly appreciated!

Thanks.

Post a Reply

Replies

Oldest  Newest  Rating
+2 Kuroodo Ditory · December 31, 2014
Let me also add in an example from my own code.

I have a class called SpriteEntity. Anything that is an entity in the game (player, enemy, spike, coin, etc) is a SpriteEntity.

The SpriteEntity class has many methods that give entities animations, collision, etc. It also has an update method that updates an entity's current position, collision, and other things.

I have a Player class that extends SpriteEntity. Since Player extends SpriteEntitiy, I can call player.update() in my game loop because the player inherits the update method from SpriteEntity.

But I have some specific functionality for the player (Specifically movement/input). that I don't want to give to any other entities. 
So in the Player class I overrided the update method from SpriteEntity and added my input functionality to the overriden method. I still want my Player's collision and position to be updated, so within the overrided method, I call super.update(). This calls the update method from the super class (SpriteEntity).

So now when I do player.update() it calls the overriden method, and then the method inside of SpriteEntitiy. So basically now it does all the code in the overriden update method, and then all the code from the method in SpriteEntity.
  • 1

Java / Android Development

107,178 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator