Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 0dae5dc

Browse filesBrowse files
committed
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
Copy full SHA for 0dae5dc

File tree

Expand file treeCollapse file tree

1 file changed

+29
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+29
-0
lines changed
+29Lines changed: 29 additions & 0 deletions
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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.