I solved the task , but i have a question .
I took only a part from the task (before we simplify it like demanded in the task) , to express what i mean simplier :
public class Main {
public static void main(String[] args) {
}
public static class NakedCat {
public NakedCat() {
super();
}
}
public static class NormalCat extends NakedCat {
public NormalCat() {
super();
}
}
}
We already know that super() is used to call the parent constructor , but the thing that confuses me here is that NakedCat is already the parent class and has no parent class , so logically calling super() in its constructor makes no sense and should make an error
I solved the task , but i have a question
Gelöst
Kommentare (1)
- Beliebt
- Neu
- Alt
Du musst angemeldet sein, um einen Kommentar schreiben zu können
Lisa L
17 April 2022, 08:14Lösung
If a class does not explicitly extend another class, then it implicitly extends Object. Object is the parent of all classes.
If no constructor is explicitly defined, the compiler automatically inserts the no-arg constructor. It does the same with the call to super().
If there is nothing special (descendant constructor calls no-arg super), then this is also done implicitly. If you want to call another super constructor, then you have to specify this with e.g. super(someArgument);
So this would be equivalent to your code above.
Usually you explicitly write the default constructor only when writing beans, when you need it (cause adding arg constructors would stop the compiler adding a no-arg ones), sometimes when you use serialization or when you use reflection (hibernate, spring...)
+2