Search code examples
javaconstructorabstract-classextends

Child classes not requiring parent constructor


I'm programming in Eclipse and have found something strange...

If I create a class like so:

public abstract class Test {
    public Test(Object obj) {}
}

Any child class would obviously require the super() to be filled in.

Same goes for:

public abstract class Test {
    public Test(Object[] obj) {}
}

So why does my IDE not complain when I do the following, and not provide a super()?

public abstract class Test {
    public Test(Object... obj) {}
}

And before you say "just run the program, it will fail", I used JUnit and the program ran fine, without providing a constructor in the extending class. My question is, why does this happen?

The child class looks like this:

public class Child extends Test {
    // Should throw error.
}

Solution

  • With this method public Test(Object... obj) you can have 0 or more params to input. By default, if the constructor does not explicitly call a parent constructor, then super() will implicitly be called. You don't have to call it explicitly because the syntax Object... obj is used for the generic case, whether you pass in an argument or not. If you want to force the user to pass in a param, then you just need to declare the argument as a List instead.