简体   繁体   中英

Why does my type-casting doesn't work with an object?

Using Java SE 11

I'm trying to make an array of instances of different classes. I would like to access a specific method of an isntance from that array. I have used type-casting, but it doesn't work.

How to tell java, that the method I tried to access is there?

The error happens at the bottom of this code. Class BillsUtilities has the showInfo method. But java gave an error, that class Object doesn't have that method.

public static void main(String[] args) {

        Object item[] = new Object[10];
        int counter = 0;
        String newItem = "BillsUtilities";

        Date date = new GregorianCalendar(2001, Calendar.OCTOBER,12).getTime();
        int amount = 50;

        switch(newItem) {
            case "BillsUtilities":
                item[counter] = new BillsUtilities(date, amount);
                break;
            case "FriendsLover":
                item[counter] = new FriendsLover(date, amount);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + newItem);
        }

        (BillsUtilities) item[counter].showInfo();
    }

easy-peasy, japanesey!

((BillsUtilities) item[counter]).showInfo();

But in general case, next snippet is more correct:

if(item[counter] instanceof BillsUtilities)
    ((BillsUtilities) item[counter]).showInfo();

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