2013-11-08 2 views
0

Я делаю программу для библиотеки; библиотека содержит различные элементы, такие как книги, видео, журналы, ЭСТ ...проблема с настройкой массива для моей программы

У меня есть класс, называемый item с основными методами для каждого элемента в библиотеке, и мои классы для book, videojournal, и все остальные элементы простираются Item. Я хочу, чтобы массив содержал все элементы в библиотеке, чтобы люди могли искать определенный элемент, он найдет его в массиве и отобразит информацию для этого элемента.

Проблема у меня в том, что, когда я создаю массив типа Item я могу только назвать методы Item класса, и я не могу назвать новые методы, которые я сделал для book в book классе или journal в класс journal.

Поэтому я вынужден иметь отдельные массивы для каждого из разных типов Items. Есть ли способ иметь только один массив, который может вызывать методы из всех разных классов для каждого элемента?

Вы можете увидеть мой код ниже; Я только прикрепил код для своего класса tester, где находится массив, сообщите мне, если вам нужно увидеть код для других классов. Буду признателен за любую помощь.

import java.util.Arrays; 
import java.util.Scanner; 
public class Library{ 
    static String title; 
    static String author; 
    static int id; 
    static int copies; 
    static String date; 
    static Book[] database = new Book[100]; 
    static Video[] database2 = new Video[100]; 
    static Journal[] database3 = new Journal[100]; 
    static CD[] database4 = new CD[100]; 
    static int count=0; 

    public static void main(String[] args){ 
    int i; 
    Scanner s = new Scanner(System.in); 
    do{ 
     System.out.println("type the adjacent number to preform that process.\n1: Add an item\n2: Checkout an item\n0: Exit program"); 
     i=s.nextInt(); 
     switch(i){ 
     case 1: 
      addItem(); 
      break; 
     case 2: 

      break; 
     } 
    }while(i != 0); 
    database[0].viewDetails(); 
    database[1].viewDetails(); 
    checkingOut(); 
    database[0].viewDetails(); 
    database[1].viewDetails(); 
    } 
    public static void addItem(){ 
    int i; 
    Scanner s = new Scanner(System.in); 
    do{ 
     System.out.println("type the adjacent number to add the item.\n1: Book\n2: Video\n3: Journal\n4: CD\n Type 0 to stop"); 
     i=s.nextInt(); 
     switch(i){ 
     case 1: 
      addBook(); 
      break; 
     case 2: 
      addVideo(); 
      break; 
     case 3: 
      addJournal(); 
      break; 
     case 4: 
      addCD(); 
      break; 
     } 
    }while(i != 0); 
    } 
    public static void addBook(){ 
    String title; 
    String author; 
    int id; 
    int copies; 
    String date; 
    int count=0; 

    Scanner s = new Scanner(System.in); 
    System.out.println("Enter the title of the book you want to add to the collection"); 
    title=s.nextLine(); 
    System.out.println("Enter the author of the book you want to add to the collection"); 
    author=s.nextLine(); 
    System.out.println("Enter the publishing date of the book you want to add to the collection"); 
    date=s.nextLine(); 
    System.out.println("Enter the ID number of the book you want to add to the collection"); 
    id=s.nextInt(); 
    System.out.println("Enter the the number of copies that will be added into the collection"); 
    copies=s.nextInt(); 

    Book Book1 = new Book(date, author, copies, id, title); 
    database[count] = Book1; 
    count++; 
    } 
    public static void addJournal(){ 
    String title; 
    String author; 
    int id; 
    int copies; 
    String date; 
    int count=0; 

    Scanner s = new Scanner(System.in); 
    System.out.println("Enter the title of the journal you want to add to the collection"); 
    title=s.nextLine(); 
    System.out.println("Enter the author of the journal you want to add to the collection"); 
    author=s.nextLine(); 
    System.out.println("Enter the publishing date of the journal you want to add to the collection"); 
    date=s.nextLine(); 
    System.out.println("Enter the ID number of the journal you want to add to the collection"); 
    id=s.nextInt(); 
    System.out.println("Enter the the number of copies that will be added into the collection"); 
    copies=s.nextInt(); 

    Journal Journal1 = new Journal(date, author, copies, id, title); 
    database3[count] = Journal1; 
    count++; 
    } 
    public static void addCD(){ 
    String title; 
    String art; 
    String genre; 
    int id; 
    int copies; 
    int date; 
    int count=0; 

    Scanner s = new Scanner(System.in); 
    System.out.println("Enter the title of the cd you want to add to the collection"); 
    title=s.nextLine(); 
    System.out.println("Enter the artist of the cd you want to add to the collection"); 
    art=s.nextLine(); 
    System.out.println("Enter the release year of the cd you want to add to the collection"); 
    date=s.nextInt(); 
    System.out.println("Enter the genre of the cd you want to add to the collection"); 
    genre=s.nextLine(); 
    System.out.println("Enter the ID number of the cd you want to add to the collection"); 
    id=s.nextInt(); 
    System.out.println("Enter the the number of copies that will be added into the collection"); 
    copies=s.nextInt(); 

    CD CD1 = new CD(date, copies, id, title, art, genre); 
    database4[count] = CD1; 
    count++; 
    } 

    public static void addVideo(){ 
    String title; 
    String director; 
    int id; 
    int copies; 
    int date; 
    String genre; 
    int count=0; 

    Scanner s = new Scanner(System.in); 
    System.out.println("Enter the title of the video you want to add to the collection"); 
    title=s.nextLine(); 
    System.out.println("Enter the director of the cd you want to add to the collection"); 
    director=s.nextLine(); 
    System.out.println("Enter the release year of the cd you want to add to the collection"); 
    date=s.nextInt(); 
    System.out.println("Enter the genre of the video you want to add to the collection"); 
    genre=s.nextLine(); 
    System.out.println("Enter the ID number of the video you want to add to the collection"); 
    id=s.nextInt(); 
    System.out.println("Enter the the number of copies that will be added into the collection"); 
    copies=s.nextInt(); 

    Video Video1 = new Video(date, copies, id, title, director, genre); 
    database2[count] = Video1; 
    count++; 
    } 

    public static void checkingOut(){ 
    boolean found=false; 
    int idSearch; 
    int i=0; 
    Scanner s=new Scanner(System.in); 
    System.out.println("Enter the ID number of the book you want to check out"); 
    idSearch=s.nextInt(); 
    while(i<database.length && found!=true){ 
     if(database[i].getIdentificationNumber() == idSearch){ 
     found = true; 
     break; 
     } 
     i++; 
    } 
    if(found==true){ 
     database[i].checkOut(); 
     System.out.println("There are "+database[i].getNumberCopies()+" copies left"); 
    } 
    else{System.out.println("There is no book with that ID number!");} 
    } 
} 
+0

Как бы массив знать тип от предмета, с которым он работал, если вы все собрали вместе? – sdasdadas

ответ

2

Вы можете проверить тип и применить его к этому типу, чтобы получить доступ к дополнительным методам.

public static void main(String args[]){ 
    for(Item item : itemList){ 
    if(item instanceof Book){ 
     Book book = (Book) item; 
     book.someBookMethod(); 
    } 
    } 
} 

хотя с помощью instanceof является considered harmful

Лучше дизайн должен был бы сделать Item абстрактные и создать методы, общие для всех детей, такие как add()

public abstract class Item{ 
    public void add(); 
    public void viewDetails(); 
} 

class Book extends Item{ 
    public void add(){ 
    //fun stuff 
    } 
    public void viewDetails(){ 
    //moar serious business logic 
    } 
} 
.... 
public static void main(String args[]){ 
for(Item item : itemList){ 
    item.add(); 
} 
} 
Смежные вопросы