I have an abstract class with an abstract method that is implemented by the child class. The implemented method in the child class should update an private instance variable of the child class. After this I want to retrieve the value of the private variable by using a getter method.
To see the problem in action I have created some sample code in playground.
Animal is the base class with the abstract method someAbstractMethod():
abstract class Animal {
protected abstract someAbstractMethod(): void;
constructor() {
document.writeln("A new animal is born<br>");
this.someAbstractMethod(); // <-- call into child class
}
}
Snake inherits from Animal and implements the abstract method someAbstractMethod(). This class has a getter/setter to retrieve the value of the private instance variable someLocalVariable:
class Snake extends Animal {
private someLocalVariable: string = "intial value";
constructor() {
super();
}
get someValue() {
document.writeln("Called getter for someValue<br>");
return this.someLocalVariable;
}
set someValue(value: string) {
document.writeln("Called setter for someValue<br>");
this.someLocalVariable = value;
}
protected someAbstractMethod() {
document.writeln("Called someAbstractMethod()<br>");
this.someLocalVariable = "now set to something new"; // <-- instance variable not updated (or in another scope)
}
}
First create a new Snake and then get the value of the private instance variable by using a getter call to sam.someValue:
let sam = new Snake();
document.writeln("Value of someValue: " + sam.someValue);
Unexpected Result
Printed Log:
A new animal is born Called someAbstractMethod() Called getter for someValue Value of someValue: intial value
sam.someValue returns 'initial value', but actually the method someAbstractMethod() was called before and should have set the value to 'now set to something new'