I have a scenario where an abstract class contains an abstract method that is then implemented by a child class. The implemented method in the child class needs to update a private instance variable specific to the child class. Subsequently, I aim to retrieve the value of this private variable using a getter method.
To demonstrate the issue, I have prepared some sample code on the playground.
Animal serves as 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 includes a getter/setter for accessing the value of the private instance variable someLocalVariable:
class Snake extends Animal {
private someLocalVariable: string = "initial 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)
}
}
Firstly, instantiate a new Snake object, followed by retrieving the value of the private instance variable via a call to sam.someValue:
let sam = new Snake();
document.writeln("Value of someValue: " + sam.someValue);
Unexpected Outcome
Console Output:
A new animal is born Called someAbstractMethod() Called getter for someValue Value of someValue: initial value
The value returned by sam.someValue is 'initial value', despite the fact that the someAbstractMethod() was called earlier and should have updated the value to 'now set to something new'