如何在 Java 中从另一个构造函数调用一个构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/285177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I call one constructor from another in Java?
提问by ashokgelal
Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?
是否可以从另一个(在同一个类中,而不是从子类中)调用构造函数?如果是如何?调用另一个构造函数的最佳方法是什么(如果有多种方法可以做到)?
采纳答案by Jon Skeet
Yes, it is possible:
对的,这是可能的:
public class Foo {
private int x;
public Foo() {
this(1);
}
public Foo(int x) {
this.x = x;
}
}
To chain to a particular superclass constructor instead of one in the same class, use super
instead of this
. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.
要链接到特定的超类构造函数而不是同一类中的构造函数,请使用super
代替this
。请注意,您只能链接到一个构造函数,并且它必须是构造函数主体中的第一条语句。
See also this related question, which is about C# but where the same principles apply.
回答by Josh
Using this(args)
. The preferred pattern is to work from the smallest constructor to the largest.
使用this(args)
. 首选模式是从最小的构造函数到最大的构造函数。
public class Cons {
public Cons() {
// A no arguments constructor that sends default values to the largest
this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
}
public Cons(int arg1, int arg2) {
// An example of a partial constructor that uses the passed in arguments
// and sends a hidden default value to the largest
this(arg1,arg2, madeUpArg3Value);
}
// Largest constructor that does the work
public Cons(int arg1, int arg2, int arg3) {
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
}
}
You can also use a more recently advocated approach of valueOf or just "of":
您还可以使用最近提倡的 valueOf 或“of”方法:
public class Cons {
public static Cons newCons(int arg1,...) {
// This function is commonly called valueOf, like Integer.valueOf(..)
// More recently called "of", like EnumSet.of(..)
Cons c = new Cons(...);
c.setArg1(....);
return c;
}
}
To call a super class, use super(someValue)
. The call to super must be the first call in the constructor or you will get a compiler error.
要调用超类,请使用super(someValue)
. 对 super 的调用必须是构造函数中的第一个调用,否则会出现编译器错误。
回答by Christian Fries
[Note: I just want to add one aspect, which I did not see in the other answers: how to overcome limitations of the requirement that this() has to be on the first line).]
[注意:我只想添加一个方面,我在其他答案中没有看到:如何克服 this() 必须在第一行的要求的限制)。]
In Java another constructor of the same class can be called from a constructor via this()
. Note however that this
has to be on the first line.
在 Java 中,可以通过this()
. 但是请注意,this
必须在第一行。
public class MyClass {
public MyClass(double argument1, double argument2) {
this(argument1, argument2, 0.0);
}
public MyClass(double argument1, double argument2, double argument3) {
this.argument1 = argument1;
this.argument2 = argument2;
this.argument3 = argument3;
}
}
That this
has to appear on the first line looks like a big limitation, but you can construct the arguments of other constructors via static methods. For example:
这this
必须出现在第一行看起来像一个大的限制,但可以通过静态方法构建其他构造函数的参数。例如:
public class MyClass {
public MyClass(double argument1, double argument2) {
this(argument1, argument2, getDefaultArg3(argument1, argument2));
}
public MyClass(double argument1, double argument2, double argument3) {
this.argument1 = argument1;
this.argument2 = argument2;
this.argument3 = argument3;
}
private static double getDefaultArg3(double argument1, double argument2) {
double argument3 = 0;
// Calculate argument3 here if you like.
return argument3;
}
}
回答by Kaamel
When I need to call another constructor from inside the code (not on the first line), I usually use a helper method like this:
当我需要从代码内部(不是在第一行)调用另一个构造函数时,我通常使用这样的辅助方法:
class MyClass {
int field;
MyClass() {
init(0);
}
MyClass(int value) {
if (value<0) {
init(0);
}
else {
init(value);
}
}
void init(int x) {
field = x;
}
}
But most often I try to do it the other way around by calling the more complex constructors from the simpler ones on the first line, to the extent possible. For the above example
但大多数情况下,我试图通过在第一行从更简单的构造函数中调用更复杂的构造函数来尽可能地反其道而行之。对于上面的例子
class MyClass {
int field;
MyClass(int value) {
if (value<0)
field = 0;
else
field = value;
}
MyClass() {
this(0);
}
}
回答by olovb
As everybody already have said, you use this(…)
, which is called an explicit constructor invocation.
正如每个人已经说过的,您使用this(…)
,这称为显式构造函数调用。
However, keep in mind thatwithin such an explicit constructor invocation statement you may not refer to
但是,请记住,在这样的显式构造函数调用语句中,您可能不会引用
- any instance variablesor
- any instance methodsor
- any inner classesdeclared in this class or any superclass, or
this
orsuper
.
- 任何实例变量或
- 任何实例方法或
- 在此类或任何超类中声明的任何内部类,或
this
或者super
.
As stated in JLS (§8.8.7.1).
如 JLS(第 8.8.7.1 节)中所述。
回答by amila isura
Within a constructor, you can use the this
keyword to invoke another constructor in the same class. Doing so is called an explicit constructor invocation.
在构造函数中,您可以使用this
关键字来调用同一类中的另一个构造函数。这样做称为显式构造函数调用。
Here's another Rectangle class, with a different implementation from the one in the Objects section.
这是另一个 Rectangle 类,其实现与 Objects 部分中的实现不同。
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(1, 1);
}
public Rectangle(int width, int height) {
this( 0,0,width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables.
此类包含一组构造函数。每个构造函数都会初始化矩形的部分或全部成员变量。
回答by ABHISHEK RANA
You can a constructor from another constructor of same class by using "this" keyword. Example -
您可以使用“this”关键字从同一类的另一个构造函数中创建构造函数。例子 -
class This1
{
This1()
{
this("Hello");
System.out.println("Default constructor..");
}
This1(int a)
{
this();
System.out.println("int as arg constructor..");
}
This1(String s)
{
System.out.println("string as arg constructor..");
}
public static void main(String args[])
{
new This1(100);
}
}
Output - string as arg constructor.. Default constructor.. int as arg constructor..
输出 - string 作为 arg 构造函数.. 默认构造函数.. int 作为 arg 构造函数..
回答by Akash Manngroliya
Yes it is possible to call one constructor from another with use of this()
是的,可以通过使用从另一个构造函数调用一个构造函数 this()
class Example{
private int a = 1;
Example(){
this(5); //here another constructor called based on constructor argument
System.out.println("number a is "+a);
}
Example(int b){
System.out.println("number b is "+b);
}
回答by Uts
Yes, any number of constructors can be present in a class and they can be called by another constructor using this()
[Please do not confuse this()
constructor call with this
keyword]. this()
or this(args)
should be the first line in the constructor.
是的,一个类中可以存在任意数量的构造函数,并且它们可以被另一个构造函数使用this()
[请不要将this()
构造函数调用与this
关键字混淆] 来调用。this()
或者this(args)
应该是构造函数中的第一行。
Example:
例子:
Class Test {
Test() {
this(10); // calls the constructor with integer args, Test(int a)
}
Test(int a) {
this(10.5); // call the constructor with double arg, Test(double a)
}
Test(double a) {
System.out.println("I am a double arg constructor");
}
}
This is known as constructor overloading.
Please note that for constructor, only overloading concept is applicable and not inheritance or overriding.
这称为构造函数重载。
请注意,对于构造函数,只有重载概念适用,不能继承或覆盖。
回答by Shiva
I will tell you an easy way
我告诉你一个简单的方法
There are twotypes of constructors:
有两种类型的构造函数:
- Default constructor
- Parameterized constructor
- 默认构造函数
- 参数化构造函数
I will explain in one Example
我将在一个例子中解释
class ConstructorDemo
{
ConstructorDemo()//Default Constructor
{
System.out.println("D.constructor ");
}
ConstructorDemo(int k)//Parameterized constructor
{
this();//-------------(1)
System.out.println("P.Constructor ="+k);
}
public static void main(String[] args)
{
//this(); error because "must be first statement in constructor
new ConstructorDemo();//-------(2)
ConstructorDemo g=new ConstructorDemo(3);---(3)
}
}
In the above example I showed 3 types of calling
在上面的例子中,我展示了 3 种类型的调用
- this() call to this must be first statement in constructor
- This is Name less Object. this automatically calls the default constructor. 3.This calls the Parameterized constructor.
- this() 对 this 的调用必须是构造函数中的第一条语句
- 这是无名称对象。这会自动调用默认构造函数。3.这将调用参数化构造函数。
Note: this must be the first statement in the constructor.
注意: 这必须是构造函数中的第一条语句。