简体   繁体   中英

Java Arraylist and inheritance calling right method. help

I created 4 classes: Cd , Dvd , Item and Database . Cd and Dvd extend from Item . The Database class stores an ArrayList of Items .

I'm stuck on creating a method in the Database class, which calls the method display in either Cd or Dvd . However I managed to display the Cds .

How can display all items? Eg

Item number = 1
CD

Item number = 2
DVD

Item number = 3
Cd

Many thanks.

Edit :

The display methods are different in Cd and Dvd .

public void displayAll() {

    for (int i = 0; i < items.size(); i++) {

        Cd theCd = (Cd) items.get(i);
        // Dvd theDVD = (Dvd) items.get(i);

        System.out.println("Item Number = " + i);
        theCd.display();

        // theDvd.display

    }

}

My class diagram is:

Class Diagram http://img571.imageshack.us/img571/1460/unledsca.png

You probably should have public abstract void display(); in your Item class. One would imagine it makes sense for Items s to be able to display themselves. Then you would implement it in CD and DVD (sounds like you already have). Then you'd have no need for the downcast:

public void displayAll()
{        
     for (int i = 0; i < items.size(); i++) {  
         Item item = (Item) items.get(i); 
         System.out.println("Item Number = " + i);
         item.display();
     }
}

And if you're using a JDK version that supports generics, consider using ArrayList<Item> instead of ArrayList . Then you can get rid of the Item cast as well.

You should get Item from the list, and not a Cd, then just invoke the methods declared in the Item class. The methods in the subclasses will automatically be invoked if they are overriding methods.

Edit: Just checked your classdiagram. The method display should be added to the Item class, and overridden by the subclasses.

You're looking for instanceof

if (item instanceof Cd)

However, as others have said ... it may point toward a bad class design. Why do you need to know what the type is?

Don't explicitly cast; that defeats the purpose of polymorphism. Declare an abstract display method in your Item base class, and then override it in Cd and Dvd .

Then your loop can be:

List<Item> my_list = new ArrayList<Item>();

...

for (int i = 0; i < items.size(); i++) {
    System.out.println("Item number = " + i);
    items[i].display();
}

This will always call the correct method.

 for (int i = 0; i < items.size(); i++) {  


     Item theItem = (Item)items.get(i); 

     System.out.println("Item Number = " + i);
     theItem.display();


 }

Cast to Item, instead of CD or DVD. Make sure Item has a display() method. Also, if you are using Java 5 or above, have a look at generics

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