Mr. Polywhirl
Mr. Polywhirl

Reputation: 48630

Flex: Access static constant from parent

Why can't I treat a static constant defined in a parent class as a attribute of the child class in Flex?

Flex

class A {
  public static const MAX:int = 100;
}

class B extends A {}

A.Max; // Valid
B.Max; // Invalid

Java

class A {
  public static final int MAX = 100;
}

class B extends A {}

A.Max; // Valid
B.Max; // Valid

Upvotes: 2

Views: 1584

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48630

Quick n' dirty hack:

In order to treat the constant MAX as a property of B, you must redefine MAX and set it equal to A.MAX:

class B extends A {
  public static const MAX:int = A.MAX;
}

Static properties not inherited

Static properties are not inherited by subclasses. This means that static properties cannot be accessed through an instance of a subclass. A static property can be accessed only through the class object on which it is defined. For example, the following code defines a base class named Base and a subclass that extends Base named Extender. A static variable named test is defined in the Base class. The code as written in the following excerpt does not compile in strict mode and generates a run-time error in standard mode.

package {
    import flash.display.MovieClip;
    public class StaticExample extends MovieClip
    {
        public function StaticExample()
        {
            var myExt:Extender = new Extender();
            trace(myExt.test);// error
        }
    }
}

class Base {
    public static var test:String = "static";
}

class Extender extends Base { }

The only way to access the static variable test is through the class object, as shown in the following code:

Base.test;

It is permissible, however, to define an instance property using the same name as a static property. Such an instance property can be defined in the same class as the static property or in a subclass. For example, the Base class in the preceding example could have an instance property named test. The following code compiles and executes because the instance property is inherited by the Extender class. The code would also compile and execute if the definition of the test instance variable is moved, but not copied, to the Extender class.

package
{
    import flash.display.MovieClip;
    public class StaticExample extends MovieClip
    {
        public function StaticExample()
        {
            var myExt:Extender = new Extender();
            trace(myExt.test);// output: instance
        }
    }
}

class Base
{
    public static var test:String = "static";
    public var test:String = "instance";
}

class Extender extends Base {}

Upvotes: 5

Related Questions