【问题标题】:Why we have more than one class constructors in a class and what its their possible use?为什么我们在一个类中有多个类构造函数以及它们的可能用途是什么?
【发布时间】:2016-06-30 16:02:13
【问题描述】:

通过阅读此处的示例http://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/

它是用

定义一个类

Todo.java

package info.androidhive.sqlite.model;

public class Todo {

int id;
String note;
int status;
String created_at;

// constructors
public Todo() {
}

public Todo(String note, int status) {
    this.note = note;
    this.status = status;
}

public Todo(int id, String note, int status) {
    this.id = id;
    this.note = note;
    this.status = status;
}

这是为什么呢?最后一个构造函数还不够?

【问题讨论】:

标签: java android


【解决方案1】:

如您所见,共有三个构造函数,但具有三个不同的参数。

第一个构造函数:

public Todo()

第二个构造函数:

public Todo(String note, int status) 

第三个构造函数:

public Todo(int id, String note, int status)

多个构造函数背后的原因是 Todo 类的对象将如何被初始化。

为了形象化我说的这个例子:Todo 对象可以用以下三种方式之一初始化:

//fist method 
Todo todoObject = new Todo();

//second method with a status of 0
Todo todoObject = new Todo("write note here", 0);

//third method whith id:1152 and status:0
Todo todoObject = new Todo(1552,"write note here", 0);

【讨论】:

    猜你喜欢
    • 2011-08-03
    • 1970-01-01
    • 2023-04-09
    • 2021-12-09
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    相关资源
    最近更新 更多