作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对以下代码有一个简短的问题
http://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/
这里使用了两个构造函数,一个带有 id,另一个没有 - 我不明白为什么。有什么好处?
我已经读过这个帖子:
Why does this class have two constructors?
我能理解的答案是,我可以创建一个带有 id 的标签,但我试图理解,如何知道它应该使用哪个构造函数?仅仅通过参数的数量吗?
public class Tag {
int id;
String tag_name;
// constructors
public Tag() {
}
public Tag(String tag_name) {
this.tag_name = tag_name;
}
public Tag(int id, String tag_name) {
this.id = id;
this.tag_name = tag_name;
}
// ...
}
最佳答案
是的,仅取决于其参数数量。
这称为函数“重载”。您可以通过提供具有不同参数的相同签名(根据它们的类型和顺序)来重载函数。
JVM 将决定在特定情况下使用哪种方法。
请注意:如果您提供构造函数,JVM 将不再提供默认构造函数。
class Foo{
private int x;
private String name;
Foo(int x){ //constructor 1
this(x, "Default Name");
}
Foo(String name){ //constructor 2
this(0, name);
}
Foo(int x, String name){ //constructor 3
this.x = x;
this.name = name;
}
}
Foo f1 = new Foo(9); //calls constructor 1, who will call constructor 3
//f1.x = 9, f1.name = "Default Name"
Foo f2 = new Foo("Test"); // calls constructor 2, who will call constructor 3
// f2.x = 0; f2.name = "Test"
Foo f3 = new Foo(3, "John"); //calls constructor 3
// f3.x = 3; f3.name = "John"
Foo f4 = new Foo() // This won't work! No default Constructor provided!
关于java - 如何在java、android中使用构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27849463/
我是一名优秀的程序员,十分优秀!