継承がどのように機能するかについて混乱しているかもしれません。特に、親クラスと子クラスの関係。
親クラスは、子サブクラスが利用できるメソッドとプロパティの形で動作を公開できます。これは、実際の動作の非常に簡単な例です。
public class Parent {
// Constructor for the Parent Class.
public function Parent() {
}
protected function sayHello() : void {
trace("Hello!");
}
}
これで、このParentクラスの子クラスを作成して、Parentの表示可能な動作(関数とプロパティ)を取得できます。
public class Child extends Parent {
// Constructor for the Child Class.
public function Child() {
// Call the 'parent' classes constructor.
super();
// This child class does not define a function called "sayHello" but
// the Parent class which this Child class extends does, and as a result
// we can make a call to it here. This is an example of how the child Class
// gains the behaviours of the Parent class.
this.sayHello();
}
public function sayGoodbye() : void {
trace("Goodbye!");
}
}
現在、子クラスが拡張する親クラスの関数とプロパティにアクセスできるこの関係は、一方向にしか機能しません。つまり、Parentクラスには、その子が宣言することを選択できる関数とプロパティについての知識がないため、次のコードは機能しません。
public class Parent {
public function Parent() {
// Trying to call the sayGoodbye() method will cause a compilation Error.
// Although the "sayGoodbye" method was declared in the Child class, the
// Parent Class has no knowledge of it.
this.sayGoodbye();
}
}
次に、親クラスからFLAのインスタンスに属するTextFieldにアクセスしようとする問題をどのように解決できるかを見てみましょう。
// it is important to note that by extending the MovieClip class, this Parent Class now
// has access to all the behaviours defined by MovieClip, such as getChildByName().
public class Parent extends MovieClip {
// This is a TextField that we are going to use.
private var txtName : TextField;
public function Parent() {
// Here we are retrieving a TextField that has an instance name of txtName
// from the DisplayList. Although this Parent Class does not have a TextField
// with such an instance name, we expect the children that extend it to declare
// one.
txtName = this.getChildByName("txtName") as TextField;
// Check to see if the Child class did have an TextField instance called
//txtName. If it did not, we will throw an Error as we can not continue.
if (txtName == null) {
throw new Error("You must have a TextField with an instance name of 'txtName' for this Parent Class to use.");
}
// Now we can make use of this TextField in the Parent Class.
txtName.text = "Hi my name is Jonny!";
}
}
これで、FLAに、この親クラスを拡張するリンケージと同じ数のインスタンスを含めることができます。親クラスがその処理を実行できるように、インスタンス名が「txtName」のTextFieldがあることを確認する必要があります。
お役に立てれば :)