Tuesday 13 August 2019

class - java: Why must I write super() in the first line of the constructor











I just learned that at school, but the teacher doesn't know why.



I can think of some good reasons, but I think there are cases when the initializing can be done later in the constructor- before you use the variables form the mother class, for example. OK, the variables should be initialized from the start, but that's not always necessary.



I"m guessing there are a more reasons for that why must super() be placed in the first line of the constructor.



So, why must I write super() in the first line of the constructor, when I'm inheriting a class?


Answer




The class you're inheriting from needs to be able to complete its construction, before you have start working on your own class.



Without doing this you could do lots of "bad" things, e.g.




  1. Pass this to another method somewhere else, which uses the base class, before its constructor has run. That would break lots of assumptions

  2. Call polymorphic functions that haven't been "set up" correctly yet. As well as anything done by the class itself the implementation possibly uses the constructor call to handle implementation internals too.



    Accessing an object before it's been constructed is bad, in the same way that fried chicken "is-a" chicken you really don't want to access (eat) that chicken before it's been fried.


  3. Access protected/public member variables of the base class which the base class was trying to promise would always be initialised to some state.





It's perfectly reasonable for a class to make a promise that any instances of it will always be in some given state. If you get a chance to do things before the constructor has been called then there's no way to honour promises like that. Essentially the "is-a" relationship wouldn't actually hold if the thing that it "is" isn't actually that thing yet!


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...