vrijdag 18 januari 2013

Inheritance


Inheritance is deriving a class from another class. 






In this example Dogs, Cats and Humans all have the same functionality as Mammals has. However Dogs and Humans (possible) have some unique functionality.

Lions, Tigers and Leopards all inheritance their functionality from Cats (so also from Mammals) and (possible) have some unique functionality themselves.





In this example both the player and the enemy derive from Sprite, (sprite is responsible for drawing the image on the screen). If the method (for example) 'Update' is called upon the player. The compiler first search for Update() in player. If it can't find 'Update()' in player it will search 'update()' in it super class (in this case the sprite class).

Duo this mechanic it is possible to derive from a class and override a method completely or you can choose to override a method but still call it base/super-method.




A simple inheritance structure example

class Sprite{
public Sprite(){
//basic constructor
}

public void Update(GameTime gameTime){
//basic update
}
}


class Player:Sprite{

public Player():
base(){
//player derives from Sprite, if it constructor is called it will also call the constructor from sprite
}


public override void Update(GameTime gameTime){
base.Update(gameTime gameTime); //if Update(gameTime) is called in player, this method also calls the update in sprite
}

}




Also i like to provide the link to the slideshow:
http://www.kevinwilmink.nl/Inheritance.pdf

Geen opmerkingen:

Een reactie posten