Among the most recognized benefits of an object-oriented programming model is inheritance.

This means that you can create a new class, typically called a subclass, that can inherit attributes from the original class, also called the parent, super, or ancestor class.

This is similar to the way you inherit characteristics from your parents. You share many things in common with a parent but also have several unique attributes.

The same can be said of classes. Through inheritance, a class can acquire from its parent useful methods and properties, as well as add entirely new methods and properties.

Inheritance syntax

First of all, you’ll need to have the extends keyword when defining the class.

public class John extends Person 

    public function John():void 


After the extends keyword, you define what class it inherits from, in this case Mover. Important to note is that a class can extend only one class at a time, and this class needs to be imported first.

The override keyword

Often a subclass inherits all superclass methods directly without making any changes to the implementations. In those cases, the method is not redeclared in the subclass.

However, there are cases in which a subclass implements a method differently than the superclass. When that occurs, you must override the method. To do that, the method must be declared as public or protected (I always use protected) in the superclass. You can then declare the method in the subclass using the override attribute.

override protected function startMoving():void {
     trace("startMoving function called in John class and not in Person class");

When overriding a method, it must have exactly the same signature as the superclass. That means the number and type of parameters and the return type of the subclass override must be exactly the same as the superclass. If they aren’t identical, the compiler throws an error.

The same goes for variables. If you want to use a variable from the parent class inside the child class, this variable must be declared in the parent class as public or protected.

Using the super keyword

Sometimes when you override a method you want the subclass implementation to be entirely different from the superclass implementation.

However, sometimes you simply want to add to the superclass implementation. In such cases, you can call the superclass implementation from the subclass implementation using the super keyword to reference the superclass:

override protected function startMoving():void {
     super.startMoving( );
     // add your new actions here


Post A Comment

Anti-Spam Quiz: