简体   繁体   中英

Type Mismatch cannot convert one type to another

So I have two classes, an Item class and a Book class that's extended from Item. In theory, Book objects should be treated as Item objects as well. I have a Book store with a collection and want to store books. It gives this error: Type mismatch: cannot convert from Collection Item to Collection Book

How do I make it so it recognizes Books as Item as well. Should be able to substitute as Item a = new Book(); Thanks!

BookStore class:

public class BookStore extends Store {
private BookType specialty;

public BookStore(Address address, String name, BookType specialty) {
    super(address, name);
    this.setSpecialty(specialty);
    addBooks();
}

public void displayAllBooksWrittenByAuthorsOverThisAge(int ageInYears) {
    Collection<Book> books = getCollectionOfItems(); // error type mismatch cannot convert from Collection<Item to Collection<Book>
    Iterator<Book> it = books.iterator();
    boolean displayedSome = false;
    while (it.hasNext()) {
        Book b = it.next();
        int ageYears = b.getDatePublished().getYear() - b.getAuthor().getBirthDate().getYear();
        if (ageYears > ageInYears) {
            System.out.println(b.getTitle() + " was written by " + b.getAuthor().getName().getLastName()
                    + " at age " + ageYears + ", which is more than " + ageInYears);
            displayedSome = true;
        }
    }
    if (displayedSome == false) {
        System.out.println("No books by authors over age " + ageInYears);
    }
}

Book class is this:

public class Book extends Item {
    private Author author;
    private Date datePublished;
    private String title;
    private BookType genre;

public Book(double weightKg, double manufacturingPriceDollars, double suggestedRetailPriceDollars, String uniqueID,
        Author author, Date datePublished, String title, BookType genre) {
    super(weightKg, manufacturingPriceDollars, suggestedRetailPriceDollars, uniqueID);
    this.author = author;
    this.datePublished = datePublished;
    this.title = title;
    this.genre = genre;
}

Item class is this:

public class Item {

private double weightKg;
private double manufacturingPriceDollars;
private double suggestedRetailPriceDollars;
private String uniqueID;

public Item(double weightKg, double manufacturingPriceDollars, double suggestedRetailPriceDollars,
        String uniqueID) {

    this.weightKg = weightKg;
    this.manufacturingPriceDollars = manufacturingPriceDollars;
    this.suggestedRetailPriceDollars = suggestedRetailPriceDollars;
    this.uniqueID = uniqueID;
}

Store Class:

public class Store {
private Address streetAddress; // instance variable of the street address.
private String name; // name of the store.
private HashMap<String, Item> itemsForSale; // store's products for sale.

/**
 * Constructor of Store.
 */
public Store(Address streetAddress, String name) {
    this.streetAddress = streetAddress;
    this.name = name;
    itemsForSale = new HashMap<>();
}
public void addItem(Item item) {
    itemsForSale.put(item.getUniqueID(), item);
}

/**
 * method that gets the item when entering key
 * 
 * @param key
 * @return itemsForSale.get(key)
 */
public Item getItemByKey(String key) {
    return itemsForSale.get(key);
}

/**
 * method that returns back all the items
 * 
 * @return itemsForSale.value()
 */
public Collection<Item> getCollectionOfItems() {
    return itemsForSale.values();
}

In BookStore class, you are calling

 Collection<Book> books = getCollectionOfItems();

which returns a collection of Item note that Book can be casted to an Item but not the other way round. So you need to change the above

Collection<Item> books = getCollectionOfItems();

If you then want to display all books, iterate over all items and check if the current item is a book before displaying it,

public void displayAllBooksWrittenByAuthorsOverThisAge(int ageInYears) {
   Iterator<Item> items = getCollectionOfItems().iterator(); 
   while (it.hasNext()) {
      Item item = it.next();
      if(item instanceof Book){
         displayBook((Book)item);
      }
   }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM