Child class constructor


#1

If the child classes inherit all the properties and methods of the parent class then why must we write a constructor method in the child class for name and other arguments, as this already exists in the parent class that we will inherit? It seems like duplication?


#2

If it is defined in the parent class and has no different parameters or implementation in the child class, you should not need to define it again… However, if it is defined in the parent class, but defined in the child class with different parameters or implementation, you would need to redefine it in order to get the proper result.

Similarly, the private instance variables of the parent class are inaccessible. Because these variables are private data of the parent class, only the parent class has access to them. The child class has no more access rights than any other class.

Which is this exercise asking for?


#3

Thank you, that’s cleared it up for me.

Inheritance III,

The code is:

class Cat extends Animal {
constructor(name, usesLitter) {
super(name);
this._usesLitter = usesLitter;
}
}

So we have to use the constructor again in the Cat child class because the Animal parent class only has “constructor(name)” and not “constructor(name, usesLItter)”?


#4

That’s correct… Because we add a new parameter, it is essentially a new constructor.


#5

So the child class constructor would overwrite the parent constructor?


#6

Yes, but only in calls to the child constructor. If a new Animal constructor is called, it still only takes parameter name, while new Cat takes parameters name,usesLitter


#7

I understand that now. And finally then… super(name)? To a beginner like me, this seems like duplication again.

Thanks for your help so far, I really appreciate it.