【问题标题】:How to use constructors in java, android?如何在java、android中使用构造函数?
【发布时间】:2015-01-08 21:03:31
【问题描述】:

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

http://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/

这里使用了两个构造函数,一个带有 id,另一个没有 - 我不明白为什么。有什么好处?

我已经阅读了这个帖子:

Why does this class have two constructors?

我能理解的答案是,我可以创建一个带有 id 而不是 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;
    }

    // ...     
}

【问题讨论】:

  • Tag tag = new Tag();,无参数构造函数; Tag tag = new Tag("name"); 带字符串参数的构造函数;程序员和编译器很容易看出区别
  • 是的,只根据传递的参数的数量和类型。
  • 是的,参数的顺序和类型构成了构造函数的签名,所以就像凯文说的那样,new Tag() 是没有任何参数的。 new Tag("string") 将是带有标签的标签。 new Tag(123, "string") 将调用构造函数 id number 和 string.. 但是 new Tag("string", 123) 会给你一个编译错误,因为没有看起来像 public Tag(String tag_name, int id)。
  • 已经提供了所有答案。但是,默认构造函数(不接受任何参数的构造函数)并不是真正需要实现的,因为当它被排除在实现之外时将由编译器定义。尝试通过查看提供的签名(因此是参数)来决定使用哪一个。
  • @RvdV79 不正确。编译器只在用户自己没有定义的时候才合成一个默认参数。

标签: java constructor default-constructor


【解决方案1】:

是的,只是参数的数量。

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

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

【讨论】:

    【解决方案2】:

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

    Tag newTag = new Tag();
    

    它会调用

     public Tag() {
    
    }
    

    但是如果你打电话给

     Tag newTag = new Tag("Name");
    

    它会调用

     public Tag(String tag_name) {
    
    }
    

    等等

    通过传递给构造函数的参数数量,它会知道调用哪个参数

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2014-03-24
        • 1970-01-01
        • 1970-01-01
        • 2010-09-22
        • 2018-02-20
        • 2011-12-15
        • 1970-01-01
        相关资源
        最近更新 更多