英文:
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":
item0+网站访问量 = new BillsUtilities(date, amount);
break;
case "FriendsLover":
item0+网站访问量 = new FriendsLover(date, amount);
break;
default:
throw new IllegalStateException("Unexpected value: " + newItem);
}
(BillsUtilities) item0+网站访问量.showInfo();
}
答案1
得分: 1
轻松简单,像日本人一样!
((BillsUtilities) item[counter]).showInfo();
但在一般情况下,下面的代码片段更正确:
if(item[counter] instanceof BillsUtilities)
((BillsUtilities) item[counter]).showInfo();
英文:
easy-peasy, japanesey!
((BillsUtilities) item0+网站访问量).showInfo();
But in general case, next snippet is more correct:
if(item0+网站访问量 instanceof BillsUtilities)
((BillsUtilities) item0+网站访问量).showInfo();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论