简体   繁体   English

为什么我的类型转换不适用于对象?

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

Using Java SE 11使用 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.我想从该数组访问 anntance 的特定方法。 I have used type-casting, but it doesn't work.我使用了类型转换,但它不起作用。

How to tell java, that the method I tried to access is there?如何告诉java,我尝试访问的方法在那里?

The error happens at the bottom of this code.错误发生在此代码的底部。 Class BillsUtilities has the showInfo method. BillsUtilities 类具有 showInfo 方法。 But java gave an error, that class Object doesn't have that method.但是java给出了一个错误,那个类Object没有那个方法。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM