In languages with dynamic typing, the use of polymorphism can lead to errors in the superclass.
I will try to explain my question with a simple example: Suppose that a language with dynamic typing (for example, ECMAScript) and the following class structure:

class A{ private idA; public A(){ idA=0; } public foo(){ update(); if (this.idA!=3) Throws new Exception(" What is happening? "); } private update(){ this.idA = 3; } } class B extends A{ private idB; public B(){ super(); idB=0; } public foo(){ super.foo();
In this very simple example, when I create an object of class B, B :: foo () calls the parent A :: foo (), which causes an “update”. The object is an instance of B, so the called update functions are called B :: update, after which the update function (B :: update) appears again in B :: foo. The end result is that A :: update is never called, and idA is still 0.
Class A works correctly if one is used, but after extending it with B, the foo () function fails.
What is the correct solution to this problem:
1) Make class A call A :: update, which means ugly code, every call to its own function (superclass protection):
A::foo(){ A::update(); if (this.idA!=3) Throws new Exception(" What is happening? "); }
2) B :: update is an extension of A :: update, so B :: update should call itself a parent function (prepare a subclass and solve problems):
B::foo(){ super.foo(); ... // Any operation that must be performed between A::update and B::update } B::update(){ super.update(); this.idB = 5; }
But in this case, it is A :: foo, which causes the update, not B :: foo. This means other problems.
3) Any other solution.
As a summary:
How to protect superclass code from polymorphism?
- Add protections to the superclass.
- The solution to this problem when creating a child class
- The tongue must do it! (I don't know if this is possible with dynamically typed languages)
I am looking for a very theoretical / canonical solution to this question.
EDITED: get the problem out of the constructor and clarify some points.