如何在java,android中使用构造函数?

问题描述 投票:0回答:3

我有一个关于以下代码的简短问题

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;
    }

    // ...     
}
java constructor default-constructor
3个回答
4
投票

是的,只能通过其参数数量。

它被称为“重载”函数。您可以通过提供具有不同参数的相同签名(根据其类型和顺序)来重载函数。

然后,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!

0
投票

**它应该使用哪种构造函数?只有它的参数量? **是的,例如,如果你打电话

Tag newTag = new Tag();

它会打电话

 public Tag() {

}

但如果你打电话

 Tag newTag = new Tag("Name");

它会打电话

 public Tag(String tag_name) {

}

等等

通过多少参数传递给构造函数,它将知道要调用哪一个


0
投票

编译器在Java Language Specification中通过规则知道“它应该使用哪个构造函数”。

简历:是通过方法的签名(参数的类型和顺序---不影响签名的异常,也是返回类型)。这不仅仅受构造函数的限制,而是任何方法,正确重载;您可以通过“重载”主题来研究这些。重载方法---或构造函数---的原因是为了提供更大的灵活性。

© www.soinside.com 2019 - 2024. All rights reserved.