Previous Page
Next Page

Recipe 2.6. Implementing Subclass Versions of Superclass Methods

Problem

You want to implement a method in a subclass differently than how it was implemented in the superclass.

Solution

The superclass method must be declared as public or protected. Use the override attribute when declaring the subclass implementation.

Discussion

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 in the superclass. You can then declare the method in the subclass using the override attribute. As an example, you'll first define a class, Superclass:

package {
    public class Superclass {
        public function Superclass(  ) {}
        public function toString(  ):String {
            return "Superclass.toString(  )";
        }
    }
}

Next, define Subclass so it inherits from Superclass:

package {
    public class Subclass extends Superclass {
        public function Subclass(  ) {}
    }
}

By default, Subclass inherits the toString( ) method as it's implemented in Superclass:

var example:Subclass = new Subclass(  );
trace(example.toString(  )); // Displays: Superclass.toString(  )

If you want the toString( ) method of Subclass to return a different value, you'll need to override it in the subclass, as follows:

package {
    public class Subclass extends Superclass {
        public function Subclass(  ) {}
        override public function toString(  ):String {
            return "Subclass.toString(  )";
        }
    }
}

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.

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:

super.methodName(  );

See Also

Recipe 2.5


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)