DEV Community

loading...

Discussion on: Does calling super() affect instances of a subclass?

Collapse
michelemauro profile image
michelemauro

That's a yes. Because it's the same instance. super() does not target another instance, it just sets up the part of your instance that is defined in the superclass.

Your sc variable is not two separate instances, one of SuperClass and one from SubClass: it is just one instance of SubClass, where a part of the state is made from all SuperClass defines. You must call super() as first thing in the subclass constructor (your code won't compile otherwise) because you must first initialize the part the instance inherits, and only after that you can go on initializing the part that the subclass defines.

Is this clearer?

Thread Thread
baenencalin profile image
Calin Baenen Author

Yes. Thank you.

Though, final question, will it not compile if I don't call super() at all?

Thread Thread
pjotre86 profile image
pjotre86

No it won't. And btw: You can skip the first constructor in your subclass. It's already inherited from the superclass, so the subclass has it as well.