具有可变参数参数的多个构造函数 [英] Multiple constructors with variable argument parameters

查看:265
本文介绍了具有可变参数参数的多个构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下两个构造函数:

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.方法调用转换文档.

  1. 原始加宽使用可能的最小方法自变量
  2. 包装器类型不能扩展为其他包装器类型
  3. 您可以将Box从int到Integer并加宽到Object,但不能将其扩展到Long
  4. 狂野搏击,拳击击败Var-args.
  5. 您可以先装箱然后加宽(int可以通过Integer变为Object)
  6. 您不能先加宽然后再框(int不能成为Long)
  7. 您不能将var-args与加宽或装箱结合使用
  1. Primitive widening uses the smallest method argument possible
  2. Wrapper type cannot be widened to another Wrapper type
  3. You can Box from int to Integer and widen to Object but no to Long
  4. Widening beats Boxing, Boxing beats Var-args.
  5. You can Box and then Widen (An int can become Object via Integer)
  6. You cannot Widen and then Box (An int cannot become Long)
  7. 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
}

以下规则定义了原始类型之间的直接超类型关系:

The following rules define the direct supertype relation among the primitive types:

  • double> 1 浮动

浮动> 1

long> 1 int

long >1 int

int> 1 字符

int> 1

short> 1 字节

这篇关于具有可变参数参数的多个构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆