Derived Classes
"Deriving" classes lets you make a classes similar to another class but change the class. This is done using the "extends" keyword. For example:
public class Goblin extends Monster {
The Goblin class now "inherits" all public and protected variables and methods of the Monster class. That brings us to the "protected" keyword. We already know what "public" and "private" mean. Protected variable can only be accessed by the class containing th variable (as with all variables) and children of the class (such as Goblin in our example). Deriving classes is most useful for creating similar but different classes. Just like our first example, you can create a generic "Monster" class and derive several different more specific monsters (like "Goblin") from it. If the parent class has a constructor, you can call the constructor with the super keyword. Like in this example which demostrates some of the functions of derived classes.
public class Monster {
private int Health;
Monster(int initHealth) {
Health = initHealth;
}
public void setHealth(int H) {
Health = H;
}
public int getHealth() {
return Health;
}
}
public class Goblin extends Monster {
Goblin(int initHealth) {
super(initHealth);
}
public AttackSelf(int Power) {
setHealth(getHealth() - Power);
}
}
The goblin has all of the variables and methods as the Monster class, but it has a new Goblin-specific method. As a matter of fact, any variable or parameter of type "Monster" can be filled with a "Goblin" instead. Because Goblins are not too bright, I gave this class a function to attack itself. This gives me another chance to explain the OOP concept to you. You can see that with these function the "Health" variable can reach a negative value. If this happens the goblin should be dead. You can set the "SetHealth" function to kill the goblin if its health becomes lower then zero.