Essential ActionScript 2.0

 <  Day Day Up  >  

Recall from Chapter 3 that every class effectively defines a custom datatype. Correspondingly, a subclass is considered a subtype of its superclass. But the term " subtype" is not just figurative; it means literally that an instance of the subtype can be used anywhere its superclass's type is expected. For example, if we create a variable, aInstance , whose type is class A , as follows :

var aInstance:A;

we can then legally assign that variable an instance of any subclass of class A :

aInstance = new B( ); // No problem.

A variable typed to a given class can legally store instances of any subclasses of that class.

The preceding assignment works because the compiler knows that any instance of class B has (through inheritance) all the methods and properties defined by class A . However, the reverse is not true. We cannot assign an instance of A to a variable whose datatype is B :

var bInstance:B = new A( ); // Error.

That assignment does not work because the compiler cannot guarantee that an instance of class A will have the methods and properties defined by class B . Hence, the compiler generates a type mismatch error:

Type mismatch in assignment statement. Found A where B is required.

We'll return to this topic later in this chapter when we study polymorphism. For a full discussion of type mismatches , again see Chapter 3.

 <  Day Day Up  >  

Категории