简体   繁体   English

子类不需要父构造函数

[英]Child classes not requiring parent constructor

I'm programming in Eclipse and have found something strange... 我在Eclipse编程,发现了一些奇怪的东西......

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. 任何子类显然都需要填写super()

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() ? 那么为什么我的IDE不会在我执行以下操作时抱怨,而不是提供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. 在你说“只运行程序,它会失败”之前,我使用了JUnit,程序运行正常,没有在扩展类中提供构造函数。 My question is, why does this happen? 我的问题是,为什么会发生这种情况?

The child class looks like this: 子类看起来像这样:

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

With this method public Test(Object... obj) you can have 0 or more params to input. 使用此方法public Test(Object... obj)您可以输入0或更多参数。 By default, if the constructor does not explicitly call a parent constructor, then super() will implicitly be called. 默认情况下,如果构造函数未显式调用父构造函数,则将隐式调用super() 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. 您不必显式调用它,因为语法Object... obj用于通用情况,无论您是否传入参数。 If you want to force the user to pass in a param, then you just need to declare the argument as a List instead. 如果要强制用户传入参数,则只需将参数声明为List

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM