Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override a setter, and the getter must also be overridden

class AbstractClass {      constructor() {     }      set property(value) {         this.property_ = value;     }      get property() {         return this.property_;     }  }  class Subclass extends AbstractClass {      constructor() {         super();     }      set property(value) {         super.property = value;         if (!(this.property_ instanceof SubclassAssociatedClass)) throw new TypeError();     }      //get property() {     //  return super.property;     //}  } 

Override the set method of an attribute and it appears the get method must be overridden also, otherwise undefined is returned (i.e., the get method is not inherited, uncomment the subclass get property() method above and everything works fine).

I assume this is a part of the spec., it would follow though possibly if the behaviour was a consequence of cross compiling. Just to be sure, is this the correct way to code overridden setters and getters (both at the same time or not at all)?

like image 232
user5321531 Avatar asked Mar 09 '15 20:03

user5321531


People also ask

Can we override getter and setter in Java?

You can always manually disable getter/setter generation for any field by using the special AccessLevel. NONE access level. This lets you override the behaviour of a @Getter , @Setter or @Data annotation on a class.

Can we use getter without setter?

Depends on if the value you are talking about is something you want to let other classes modify - in some cases the answer is yes, in some it is no. If the answer is no then there is no reason to add a setter method and in fact it might harm things.

How do I override a TypeScript method?

To override a class method in TypeScript, extend from the parent class and define a method with the same name. Note that the types of the parameters and the return type of the method have to be compatible with the parent's implementation. Copied! class Parent { doMath(a: number, b: number): number { console.


1 Answers

Yes, this is intentional (a part of the spec). If an object has an own property (.property in your example), this property will be used and not an inherited one. If that property is existent, but is an accessor property without a getter, then undefined will be returned.

Notice that this behaviour has not changed from ES5.

like image 90
Bergi Avatar answered Oct 10 '22 18:10

Bergi