Der Konstruktor von FileInputStream soll doch nur aufgerufen werden, wenn es sich um eine .txt Datei handelt - warum kann ich also nicht erst die entsprechende if-Bedingung schreiben, in der die Exception geschmissen wird, und danach erst super(filename) ?
Kathi144
Level 18
Warum muss der Aufruf von super die erste Anweisung im Konstruktor sein?
Gelöst
Kommentare (1)
- Beliebt
- Neu
- Alt
Du musst angemeldet sein, um einen Kommentar schreiben zu können
Guadalupe Gagnon
24 Mai 2023, 15:34
It is a rule in Java that if you call the parent's constructor it MUST be the very first line in the constructor. It is illegal to do so otherwise. Furthermore, if the parent class does not have a default constructor then a child class MUST call one of the parent's constructors in its own constructors.
This is logical in that the purpose constructors of constructors are to ensure that objects are initialized to a valid state. If you need to have logic to decide which valid state to initialize the proper place would be prior to initializing a new object.
Take this short example:
You have a parent class (A) and a child class (B). In this example the parent class does not have a default constructor so it is a requirement that any child class call one of the parent's constructors. Java doesn't care which one is called, only that one is, and that is for each constructor in the child class. In the child class I put constructors that have different parameters than constructor's of the parent, which is valid in Java, the point is that each constructor MUST call any one of the parent class's constructors.
In my example the code doesn't really do anything of value, however in code designed for a purpose the constructor calls should be logical. +2