【问题标题】:Parent Arraylist containing 2 child class包含 2 个子类的父 Arraylist
【发布时间】:2021-11-24 07:59:30
【问题描述】:

首先,如果标题具有误导性,我很抱歉。我是编程新手,不知道如何正确描述我的问题。

这是我的代码,我有 1 个父类和 2 个扩展父类和 1 个主类的子类。

Book.java

public class Book {
    private String bookTittle;
    private String bookAuthor;

    public Book(String tittle, String author)
    {
        this.bookTittle = tittle;
        this.bookAuthor = author;
    }

    public String getTittle()
    {
        return bookTittle;
    }

    // other getter and setter
}

Science.java

public class Science extends Book {
    private int SciID;

    public Science(String tittle, String author, int ScienceID)
    {
        super(tittle, author);
        this.SciID = ScienceID;
    }

    // setter and getter
}

小说.java

public class Fiction extends Book {
    private int fictId;

    public Fiction(String tittle, String author, int fictionID)
    {
        super(tittle, author);
        this.fictId = fictionID;
    }

    // setter and getter
}

LibraryMain.java

import java.util.*;
public class LibraryMain {
    private ArrayList<Book> LibBook = new ArrayList<>();

    
    public LibraryMain()
    {
        LibBook.add(new Science("Frog", "June", 101));
        LibBook.add(new Fiction("TimeTravel", "Kiel", 201));
    }

    public boolean bookSearch(String bookTittle)
    {
        for (int i = 0;i<LibBook.size();i++)
        {
            if(LibBook.get(i).getTittle().equalsIgnoreCase(bookTittle)){
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        LibraryMain mainLib = new LibraryMain();
        Scanner in = new Scanner(System.in);
        System.out.println("--Search book--");
        System.out.print("Book tittle: ");
        String tittle = in.nextLine();
        if(mainLib.bookSearch(tittle)){
            System.out.println("Book Found!");
        }
        else{
            System.out.println("Not Found");
        }
    }


}

目前LibraryMain上的方法只能查找该书是否存在于arraylist中,有没有办法知道这本书来自哪个类?

当前结果是

--Search book--
Book tittle: frog
Book Found!

我希望结果如何

--Search book--
Book tittle: frog
Book Found! frog is a science book

【问题讨论】:

  • 如果要获取对象的类型,可以使用getClass()(例如Book b = new Science(); b.getClass(); //returns Science.class)或使用instanceof(例如if(b instanceof Science) { ...})进行检查。然而,依赖继承而不关心类型(取决于需求和设计)或者在需要时返回一些标识符可能会更好。
  • 顺便说一句 - 让 'Book' 类包含一个名为 'Genre' 的字段通常更有意义,而不是每个类型都是它们自己的类。
  • 我正在尝试学习 oop 和 arraylist,这导致我将它们变成了一个不同的类

标签: java


【解决方案1】:

要扩展我的评论,您首先必须将书从bookSearch(...) 退回,即

public boolean bookSearch(String bookTitle) {
    for (Book book : libBook) {
        if(book.getTittle().equalsIgnoreCase(bookTittle)) {
            return book;
        }
    }
    return null;
}

使用instanceof

那么你可以使用instanceof

Book b = bookSearch("some title");

//if b is null this will be false
if( b instanceof Science ) { 
  //Science book found
} else if( b instanceof Fiction ) {
} ...

使用继承

如您所见,这可能会变得很长,因此对于您的情况,最好将描述添加到书籍本身,例如像这样:

class Book {
  private final String typeDesc;

  protected Book(String desc, ...) {
    typeDesc = desc;
  }

  public String getTypeDesc() {
    return typeDesc;
  }

  ...
}

class ScienceBook extends Book {
  public ScienceBook() {
    super("science book");
  }

  ...
}

或者提供getTypeDesc()作为抽象方法并像这样实现

public String getTypeDesc() {
    return "science book";
  }

然后像这样使用它:

Book b = bookSearch("some title");

if( b != null ) { 
  System.out.println(b.getTitle() + " has been found, it is a " + b.getTypeDesc() );
} 

使用 getClass()

如果您不希望书籍本身的描述(例如,如果在某些用例中可能需要不同),您也可以将类用作映射键,例如像这样:

Map<Class<?>, String> typeDescriptions = new HashMap<>();
typeDescriptions.put(ScienceBook.class, "science book");
typeDescriptions.put(FictionBook.class, "fiction book");

然后使用getClass()并在地图中查找描述:

Book b = bookSearch("some title");

if( b != null ) { 
   //look up the description based on the book class and return it, 
   //if none can be found return the default value "generic book"
   String typeDesc = typeDescriptions.getOrDefault(b.getClass(), "generic book");
   System.out.println(b.getTitle() + " has been found, it is a " + typeDesc );
} 

【讨论】:

  • 我使用了 getTypeDesc 方法,它成功了!并非常感谢您提供多种方法来做到这一点
【解决方案2】:

在父类中添加抽象方法String getDescription(),然后在每个子类中定义,返回描述字符串。

【讨论】:

    【解决方案3】:
     public String bookSearch(String bookTittle)
        {
            for (int i = 0;i<LibBook.size();i++)
            {
                if(LibBook.get(i).getTittle().equalsIgnoreCase(bookTittle)){
                    return LibBook.get(i).class.getSimpleName();
                }
            }
            return null;
        }
    

    在主函数之后:

    public static void main(String[] args) {
            LibraryMain mainLib = new LibraryMain();
            Scanner in = new Scanner(System.in);
            System.out.println("--Search book--");
            System.out.print("Book tittle: ");
            String tittle = in.nextLine();
            String foundbook = mainLib.bookSearch(tittle)
            if(foundbook != null){
                System.out.println("Book Found! %s",foundbook);
            }
            else{
                System.out.println("Not Found");
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      • 2020-01-04
      • 1970-01-01
      相关资源
      最近更新 更多