在Book类中创建author对象时遇到了麻烦。这确实是Homework,我自己想出了所有方法,并且一直盯着这项作业两个小时。任何提示提示将不胜感激。我相信我只允许这个带有3个参数的Author构造函数,否则我将成为一个没有参数的Author构造函数,问题将会消失。
public class Author {
protected String name;
protected String email;
protected 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 String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public char getGener()
{
return gender;
}
public String toString()
{
return ( name + "(" + gender + ")@" + email);
}
}
public class Book extends Author{
private String name;
private Author author;
private double price;
private int qtyInStock = 0;
public Book(String name, Author author,Double price)
{
this.author = new author;
this.name = name;
this.price = price;
}
public Book(String name, Author author, double price, int qtyInStock)
{
this.name = name;
this.author = author;
this.price = price;
this.qtyInStock = qtyInStock;
}
public String getName()
{
return name;
}
public Author getAuthor()
{
return author;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}
public int getQtyInStock()
{
return qtyInStock;
}
public void setQtyInStock(int qtyInStock)
{
this.qtyInStock = qtyInStock;
}
public String toString()
{
return (name + " by " + author + "(" + super.gender + ")at" + super.email);
}
}
最佳答案
Book extends Author
似乎很奇怪。 Book
不是Author
。
我认为您想做的是创建一个具有Book
的Author
对象,但是您已经将Author
传递给您的Book
构造函数,那是什么问题呢?
class Book {
public Book(String title, Author author) {
this.title = title;
this.author = author;
}
}
如果您想知道如何创建
Author
,请先创建它,然后再将其传递给Book
。Author author = new Author("bob", "[email protected]", 'm');
Book book = new Book("some title", author);
那有意义吗?
关于java - Java在子类中创建对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35860475/