In Actionscript 3 I can't declare vars in Interfaces. I don't get it. I know i can work this around by defining getters and setters, but what if i just want a simple public property? I usually use getters and setters if there is something to do when i set or get a property, but what if i just want to store a value?
I'm not an actioscript programming, but interfaces (in java for example) are meant to define behavior not state, so intrerfaces in jave simply declare methods that the class implemeting the interface needs to define. Properties (or instance variable) are not in general necessary to define behavior and there are disallowed in interfaces.
You can put it like this: interfaces exist because in your language you can't inherit from multiple abstract base classes. If AS3 would have allowed you to do that, it would probably not have 'interfaces', but 'pure abstract classses'.
In other words, having properties implementation in your interface would lead to name clashes and from there to other multiple inheritance problems (diamond).
However, having just a getter or a setter with no implementation should work.
public interface I { function get A():int; }
(I don't have the AS3 compiler at hand)
A property in most programming languages that support them have two distinct parts that you need to separate:
- The external definition (ie. what is the property name, what is its type, what meta-data is associated with it)
- The internal definition (ie. what does it do in order to store and/or retrieve its value)
An interface is only ever concerned about the external definition. The interface stipulates a contract by saying "all classes that implement this interface will have this property with this specific name, and this specific type". However, what it does when you access it, that's left to that specific class.
That's also the reason why you cannot define variables in interfaces (in all the languages I know of). Doing that would add an implementation detail that the class would have to implement. Basically it would say "any class that implements this interface will have a publicly available variable with this name and type". A variable, however, does not have an internal definition, so there's no way for the class to add behaviour, for instance to provide a calculation when read from, or a security check when written to.