gpt4 book ai didi

java - 在一个类中的另一个类中使用 java 构造函数参数

转载 作者:行者123 更新时间:2023-12-02 03:43:46 27 4
gpt4 key购买 nike

我在 .Author 中有这个构造

package author;

public class Author {
private String name;
private String email;
private char gender;

public Author (String name, String email, char gender) {
this.name = name;
this.email = email;
this.gender = gender;
}
public String getName () {
return name;
}
public char gender () {
return gender;
}
public String getEmail () {
return email;
}
public void SetEmail (String userEmail) {
email = userEmail;
}
public String toString () {
return "Author info: " + " [name: " +name + ", " + " gender: " + gender +", " + " email " + email + "]";
}

}

我有另一个名为 .Book 的类,我想在 .Book 内的另一个构造中使用 Author 构造中的“name”变量,如下所示:

public class Book {
private String bookName;
private String author;
private double price;
private int qty;

public Book (String bookName, Author name, double price) {
this.bookName = bookName;
// here I'm getting an error saying ";" required
this.author = Author name;
this.price = price;
}

}

我收到一个错误(如第二个代码所示),很明显我做得不对,也不知道如何做。有什么帮助吗?

最佳答案

public class Book {
private String bookName;
private Author author; //it should be Author, not String
private double price;
private int qty;

public Book (String bookName, Author name, double price) {
this.bookName = bookName;
this.author = name; //here was ur mistake
this.price = price;
}

}

试试这个代码。假设,在编写这本书时,您确实喜欢

Book book = new Book("name", new Author("name", "name@mail", m), 22.0);

关于java - 在一个类中的另一个类中使用 java 构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36531613/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com