With a strong increase in the number of fields and methods of a class, there is a desire to divide it into semantic parts and aggregate them into the main class as field objects. But the problem is that the descendants of the main class raise the question of extending the functionality, and for this you want to inherit from the aggregated classes the expanded new ones and replace the old ones with them. And this just can not be done! Example (ActionScript 3, all classes are scattered over the same file):
public class ContainerA { public var subClass: SubClassA; public function ContainerA() { initSubclasses(); } protected function initSubclasses(): void { subClass = new SubClassA(); } } public class ContainerB extends ContainerA { // ΠΎΡΠΈΠ±ΠΊΠ° ΠΊΠΎΠΌΠΏΠΈΠ»ΠΈΡΠΎΠ²Π°Π½ΠΈΡ! ΠΏΠ΅ΡΠ΅Π³ΡΡΠΆΠ°ΡΡ ΠΌΠΎΠΆΠ½ΠΎ ΡΠΎΠ»ΡΠΊΠΎ ΠΌΠ΅ΡΠΎΠ΄Ρ override public var subClass: SubClassB; public function ContainerB() { super(); } override protected function initSubclasses(): void { subClass = new SubClassB(); } } public class SubClassA { public function PrintA(): void { trace("I'm a subclass A"); } } public class SubClassB extends SubClassA { override public function PrintA(): void { trace("I'm a subclass B, inherited from A"); } public function PrintB(): void { trace("I'm a subclass B"); } }
code in Main.as:
var containerA: ContainerA = new ContainerA(); var containerB: ContainerB = new ContainerB(); containerA.subClass.PrintA(); // " I'm a subclass A " containerB.subClass.PrintA(); // " I'm a subclass B, inherited from A " containerB.subClass.PrintB(); // Π½Π°ΠΏΠ΅ΡΠ°ΡΠ°Π»ΠΎΡΡ Π±Ρ " I'm a subclass B "
Even if, instead of overloading the field, you do an overload of the get method and access the aggregated class through it, a compilation error will also occur, but this is different: you cannot change the signature of the overloaded method:
in ContainerA:
public function getSubClass(): SubClassA { return subClass; }
in ContainerB:
override public function getSubClass(): SubClassB { return (subClass as SubClassB); }
Therefore, the question is: how are these problems solved (if they are solved) in ActionScript and how are they solved in other statically typed languages ββ(Java, C #). Maybe there are some crutch, but convenient design patterns?