为什么我的类型转换在使用对象时不起作用?

huangapple go评论78阅读模式
英文:

Why does my type-casting doesn't work with an 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();
}
英文:

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
0
+
网站访问量
= new BillsUtilities(date, amount); break; case "FriendsLover": item
0
+
网站访问量
= new FriendsLover(date, amount); break; default: throw new IllegalStateException("Unexpected value: " + newItem); } (BillsUtilities) item
0
+
网站访问量
.showInfo(); }

答案1

得分: 1

轻松简单,像日本人一样!

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

但在一般情况下,下面的代码片段更正确:

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

easy-peasy, japanesey!

((BillsUtilities) item
0
+
网站访问量
).showInfo();

But in general case, next snippet is more correct:

if(item
0
+
网站访问量
instanceof BillsUtilities) ((BillsUtilities) item
0
+
网站访问量
).showInfo();

huangapple
  • 本文由 发表于 2020年10月23日 23:50:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64503307.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定