具有可变参数参数的多个构造函数 [英] Multiple constructors with variable argument parameters
问题描述
给出以下两个构造函数:
Given these two constructors:
SomeClass(int... params)
{
// Do things
}
SomeClass(long... otherParams)
{
// Do other things
}
实例化对象foo会发生什么?
What happens when an object foo is instantiated?
SomeClass foo = new SomeClass();
未定义的默认构造函数是否以某种方式被调用?还是那些名为空数组的构造函数之一?如果是这样,先例是什么?
Is the undefined default constructor somehow called? Or is one of those constructors with an empty array called? If so, what’s the precedent?
我进行了一些基本测试,发现如果定义了不带参数的构造函数,则该构造函数将被调用.否则,会出现一个模棱两可的东西.
I’ve done some basic testing and found that if a constructor without parameters is defined then that will be called. Otherwise, it appears that an ambiguous one is called.
推荐答案
按照根据下面的Java问题"是Java编译器用于选择要调用的方法签名的规则.它们基于 JLS 5.3.方法调用转换文档.
- 原始加宽使用可能的最小方法自变量
- 包装器类型不能扩展为其他包装器类型
- 您可以将Box从int到Integer并加宽到
Object
,但不能将其扩展到Long
- 狂野搏击,拳击击败Var-args.
- 您可以先装箱然后加宽(
int
可以通过Integer
变为Object
) - 您不能先加宽然后再框(
int
不能成为Long
) - 您不能将var-args与加宽或装箱结合使用
- Primitive widening uses the smallest method argument possible
- Wrapper type cannot be widened to another Wrapper type
- You can Box from int to Integer and widen to
Object
but no toLong
- Widening beats Boxing, Boxing beats Var-args.
- You can Box and then Widen (An
int
can becomeObject
viaInteger
) - You cannot Widen and then Box (An
int
cannot becomeLong
) - You cannot combine var-args, with either widening or boxing
由于两个构造函数都是var-args(规则7),因此编译器将退回到其他规则,并选择使用最小类型的方法(规则1).
Because both constructors are var-args (rule 7) the compiler will fall back to other rules and select the method that uses the smallest type (rule 1).
您可以使用以下代码确认此行为:
You can confirm this behaviour with following code:
static class SomeClass {
SomeClass(long... value) { System.out.println("Long"); }
SomeClass(int... value) { System.out.println("Int"); }
SomeClass(byte... value) { System.out.println("Byte"); }
}
public static void main(String[] args) throws Exception {
SomeClass o = new SomeClass(); // Byte
}