Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

java - 如何在Java中从另一个调用一个构造函数?(How do I call one constructor from another in Java?)

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)?

(调用另一个构造函数的最佳方法是什么(如果有几种方法可以做到)?)

  ask by ashokgelal translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 .

(要链接到特定的超类构造函数而不是同一类中的构造函数,请使用super代替this 。)

Note that you can only chain to one constructor , and it has to be the first statement in your constructor body .

(请注意, 您只能链接到一个构造函数 ,并且它必须是构造函数主体中的第一条语句 。)

See also this related question , which is about C# but where the same principles apply.

(另请参见 C#有关但适用相同原理的相关问题 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...