简体   繁体   English

无参构造函数调用2参数构造函数

[英]No-argument constructor calling 2-argument constructor

I am trying to call to make a 2-arg constructor the default constructor. 我试图调用使2-arg构造函数成为默认构造函数。 By this I mean; 我的意思是这个; when the no-arg constructor is called, it calls the 2-arg constructor with default values. 当调用no-arg构造函数时,它使用默认值调用2-arg构造函数。

public class Foo
{
  int foo1;
  int foo2;

  public Foo()
  {
    Foo(0, 0); //error          //I also tried this.Foo(0,0);
  }
  public Foo(int one, int two)
  {
    this.foo1 = one;
    this.foo2 = two;
  }
}

How do I call the 2nd constructor? 我如何调用第二个构造函数?

Just write 写吧

public Foo()
{
    this(0, 0);
}

Note that it has to be the very first thing in the constructor. 请注意,它必须是构造函数中的第一件事。

(This is specified in §8.8.7.1 "Explicit Constructor Invocations" of The Java Language Specification, Java SE 8 Edition , which also specifies how to invoke a specific superclass constructor.) (这在Java语言规范Java SE 8 Edition的 §8.8.7.1“显式构造函数调用”中指定,它还指定了如何调用特定的超类构造函数。)

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

相关问题 隐式调用超类中的无参数构造函数 - Calling no-argument constructor in superclass implicitly 使用2参数构造函数创建对象时出现问题 - Problem creating an object with 2-argument constructor Exception或其子类中的无参数构造函数 - No-argument constructor in Exception or its subclasses 强制超类包含无参数构造函数 - Force superclasses to include a no-argument constructor 在编译时强制存在无参数构造函数(Java) - Enforce presence of no-argument constructor at compile time (Java) 为无参数构造函数的类创建动态代理 - Create a dynamic proxy for a class without no-argument constructor Firebase数据库:尽管存在错误,但仍出现“无参数构造函数”错误 - Firebase Database: Getting “No-Argument Constructor” Error Despite Having It Scala类的最终def this()声明没有公共的无参数构造函数 - Scala class final def this() declares no public no-argument constructor Android Firebase数据库异常:未定义无参数构造函数 - Android Firebase Database exception: not define a no-argument constructor 即使子类已经有一个已定义的构造函数,父类是否总是需要一个默认或无参数的构造函数? - Does a parent class always need a default or no-argument constructor even if the child class already has a defined constructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM