Skip to content

Commit 0dae5dc

Browse files
committedSep 12, 2015
how do i call one constructor from another in java
how do i call one constructor from another in java
1 parent ef18c04 commit 0dae5dc

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
##能否在一个构造器中调用另一个构造器
2+
3+
###问题
4+
能否在一个构造器中调用另一个构造器(在同一个类中,不是子类)?如果可以会怎样?
5+
那么调用另一个构造器的最好方法是什么(如果有几种方法可以选择的话)?
6+
7+
8+
###回答
9+
这样做是可以的。
10+
```java
11+
public class Foo
12+
{
13+
private int x;
14+
15+
public Foo()
16+
{
17+
this(1);
18+
}
19+
20+
public Foo(int x)
21+
{
22+
this.x = x;
23+
}
24+
}
25+
```
26+
如果你想链接到一个特定的父类构造器而不是本类的话,这里应该使用super,而不是this.
27+
请注意,你只能链接到一个构造器,并且调用语句必须是这个构造器的第一个语句。
28+
stackoverflow原址:
29+
http://stackoverflow.com/questions/15182496/why-does-this-code-using-random-strings-print-hello-world

0 commit comments

Comments
 (0)
Please sign in to comment.