+ 1
What are few real time examples for interface, abstract-classes and inheritance.
2 Respuestas
+ 12
what the heck is this, feudalism? I don't want to inherit a dang barony I just want to program
+ 2
INHERITANCE
A simple example of inheritance can be seen in games. In an average action game there are a lot of different enemies. Animals, Humans, Undead... All kinds of bad guys. If you want to program their classes, it is very usefull to be able to have some set of shared method's to be able to manipulate all the enemies. If you want to move an enemie, you don't want to have to call Animal.move() for Animals, but Undead.changePosition() for undead.
It would be way more efficient to have them all share the same basic ruleset.
You could define this ruleset in a superclass called 'Enemy' and then have all types of enemies extends the 'Enemy'-class.
If the Enemy class has a 'move()'-method, all children of the Enemy-class also have that emthod.
This ensures you can always call on the same methods without error. So now any kind of Enemy kan move with the same command.
ABSTRACT CLASSES
Abstract classes are used whenever you want to define a basic ruleset, or properties for all of the children-classes, but not want this 'superçlass' to be instantiated.
Example: In the above code we defined an 'Enemy'-class, but we don't want to create objects of the 'Enemy'-class. We want Aniaml, Undead or Human-objects, which have their own behaviour.Therefor we define the Enemy-class as an abstract class.
INTERFACES
Interfaces are, for example, used in graphical user interfaces in Java. Whenever you want something to happen when the user presses a button, you use the ActionListener-interface. This interfaces requires you to have a certain piece of code that handles the button click (an ActionEvent).