Java问题使用字符串参数实例化对象

时间:2012-05-29 00:06:33

标签: java string instantiation

我正在尝试执行我的任务但是我在实例化具有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());
}
}

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

2 个答案:

答案 0 :(得分:7)

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

您是将参数设置为属性值 - 可能是您想要的倒退?

答案 1 :(得分: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();
}