我无法掌握这些构造函数的用法。
我理解一个如下:
public book(){
private string author;
private string title;
private int reference;
}
一个参数化的构造函数如下:
public book( string author, string title, int reference){
}
但是,这将如何在主要方法中使用?
我无法掌握这些构造函数的用法。
我理解一个如下:
public book(){
private string author;
private string title;
private int reference;
}
一个参数化的构造函数如下:
public book( string author, string title, int reference){
}
但是,这将如何在主要方法中使用?
您可以通过三种方式拥有构造函数:
1)你声明一个无参数的
.
public class book
{
string author;
string title;
int reference;
public book() {
// initialize member variables with default values
// etc.
}
}
2) 你用参数声明一个
.
public class book
{
string author;
string title;
int reference
public book(string author, string title, int reference) {
// initialize member variables based on parameters
// etc.
}
}
3)你让编译器为你声明一个——这要求你不要声明你自己的一个。在这种情况下,成员变量将根据它们的类型提供一个默认值(本质上是调用它们的无参数构造函数)
您可以混合使用选项 1) 和 2),但 3) 是独立的(不能与其他两个中的任何一个混合使用)。您还可以拥有多个带参数的构造函数(参数类型/编号必须不同)
使用示例:
public static void main(String[] args) {
String author = ...;
String title = ...;
int ref = ...;
book book1 = new book(); // create book object calling no-parameter version
book book2 = new book(author, title, ref); // create book object calling one-parameter
// (of type String) version
}
从语法上讲,如何使用它们...
书 b1 = 新书(); book b2 = new book("我的书名", "我的作者", 0);
你调用第一个来创建一本空书。可能还有 setTitle(String title)、setAuthor(String author) 和 setReference(int ref) 方法。这看起来像......
书 b1 = 新书(); // 做一些事情来获取标题作者和参考 b1.setTitle(标题); b1.setAuthor(作者); b1.setReference(参考);
如果您在构建图书实例时没有可用的标题、作者和参考资料,则可以调用它。