簡體   English   中英

用字符串參數實例化對象的Java問題

[英]Java Problems instantiating object with string parameter

我正在嘗試進行分配,但是在實例化具有String參數的對象時遇到問題。 到目前為止,當我編譯和運行應用程序的內容時,它將返回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());
}
}

我不知道是什么問題。 誰能幫助我? 我也有一個非小說類的子類,但是我還沒到那個地步。

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

您正在將參數設置為屬性值-可能是您想要的倒退了?

您的課程應該是這樣的-

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM