2

first i am sorry if the tittle is misleading. I am kind of new to programing and don't know how to describe my problem correctly.

Here is my code, i have 1 parent class, and 2 child class that extend the parent and 1 main class.

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
}

Fiction.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");
        }
    }


}

Currently the method on LibraryMain can only find if the book exist in the arraylist or not, is there anyway to know from which class the book came from?

Current result is

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

How i wanted the result to be

--Search book--
Book tittle: frog
Book Found! frog is a science book
Deni
  • 23
  • 3
  • If you want to get the type of an object, you could use `getClass()` (e.g. `Book b = new Science(); b.getClass(); //returns Science.class`) or check using `instanceof` (e.g. `if(b instanceof Science) { ...}`). However, it might be better to either rely on inheritance and not bother with the type (depends on the requirements and design) or return some identifier if needed. – Thomas Nov 24 '21 at 08:05
  • Does this answer your question? [How to check if a subclass is an instance of a class at runtime?](https://stackoverflow.com/questions/2410304/how-to-check-if-a-subclass-is-an-instance-of-a-class-at-runtime) – Joe Nov 24 '21 at 08:19
  • 3
    Just as an aside - It would typically make more sense to have the 'Book' class contain a field called 'Genre' instead of each genre being a class of their own. – jdkramhoft Nov 24 '21 at 08:21
  • i am trying to learn oop and arraylist which caused me to make them into a diffrent class – Deni Nov 24 '21 at 08:45

3 Answers3

2

Add an abstract method String getDescription() into parent class and then define it in every child class to return the describing string.

Serge Iroshnikov
  • 749
  • 1
  • 6
  • 17
2

To expand on my comment, you'd first have to return the book from bookSearch(...), i.e.

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

Using instanceof

Then you could use 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 ) {
} ...

Using inheritance

As you can see this can get quite lengthy, so for your case it might be better to add the description to the books themselves, e.g. like this:

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

  ...
}

Or provide getTypeDesc() as an abstract method and implement it like

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

Then use it like this:

Book b = bookSearch("some title");

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

Using getClass()

If you don't want the description on the books themselves (e.g. if it might need to be different in certain use cases) you can also use the class as a map key, e.g. like this:

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

Then use getClass() and lookup the description in the map:

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 );
} 
Thomas
  • 87,414
  • 12
  • 119
  • 157
  • i used the getTypeDesc method and it worked! and thanks a lot for giving variety of method to do it – Deni Nov 24 '21 at 08:48
0
 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;
    }

After that on main function:

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");
        }
    }
Poran
  • 532
  • 4
  • 9