1

我正在尝试完成我的作业,但在实例化具有 String 参数的对象时遇到问题。当我编译并运行到目前为止我拥有的应用程序时,它返回“Null”的字符串值,而不是我期望的值。

这是我的抽象超类

public abstract class Book
{
//Declaration of class variable
private String title;
protected double price;

// contructor for Book class objects
public Book(String bookTitle)
    {
        bookTitle = title;
    }
//method that gets and returns books title
public String getTitle()
    {
        return title;
    }
//method that gets and returns books price
public double getPrice()
    {
        return price;
    }
//abstract method with no parameters
public abstract void setPrice();
}

这是我的子类

public class Fiction extends Book
{
//subclass contructor
public Fiction(String bookTitle)
{
    //calling superclass constructor
    super(bookTitle);
}
//override annotation and setPrice method override
@Override
public void setPrice()
{
    price = 19.99;
}
}

这是我的主要方法类,对象fictionBook 应该用标题The White Unicorn 进行实例化。但是,由于某种原因,我的 println 正在打印出 null

public class BookTester
{
//Main method
public static void main(String[] args)
{
    //Instantiate object
    Fiction fictionBook = new Fiction("The White Unicorn");
    NonFiction nonFictionBook = new NonFiction("Autobiography of Curtis Sizemore");
    //call to the setPrice() method
    fictionBook.setPrice();
    nonFictionBook.setPrice();
    //Print information on books
    System.out.println("The Fiction book titled \"" + fictionBook.getTitle() + "\"costs $" + fictionBook.getPrice());
}
}

我无法弄清楚问题是什么。任何人都可以帮助我吗?我也有一个非小说类书籍的子类,但我还没有达到这一点。

4

2 回答 2

7
public Book(String bookTitle)
    {
        bookTitle = title;
    }

您正在将参数设置为属性值 - 可能与您的意图相反?

于 2012-05-29T00:09:03.710 回答
1

你的课应该是这样的——

public abstract class Book
{
//Declaration of class variable
private String title;
protected double price;

// contructor for Book class objects
public Book(String bookTitle)
    {
        this.title = bookTitle;
    }
//method that gets and returns books title
public String getTitle()
    {
        return this.title;
    }
//method that gets and returns books price
public double getPrice()
    {
        return this.price;
    }
//abstract method with no parameters
public abstract void setPrice();
}
于 2012-05-29T07:30:48.843 回答