创建不同的对象的实例列表,并使用这些对象 [英] Creating instance list of different objects and using these objects
本文介绍了创建不同的对象的实例列表,并使用这些对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Java的code:
进口的java.util.ArrayList;
进口的java.util.List;苹果类{
INT价格;公共无效myFunction的(INT iPrice)
{
价格= iPrice;
}
}橙类{
INT价格;公共无效myFunction的(INT iPrice)
{
价格= iPrice;
}
}公共类主要{公共静态无效的主要(字串[] args){
清单<对象>名单=新的ArrayList<>(); //创建3个苹果对象名单
list.add(新苹果());
list.add(新苹果());
list.add(新橙()); list.get(0)。 / *得到(0)。这是不使用苹果的对象,我的功能* /}
}
解决方案
该方法 list.get(0)
返回对象
的参考,因此,你必须垂头丧气它转换为苹果
。有点像这样的:
苹果=(苹果)list.get(0);
然后调用该函数。
请注意:这是一个很好的做法,在Java类名称以大写字母如苹果
,橙色
Java code:
import java.util.ArrayList;
import java.util.List;
class apple{
int price;
public void myFunction(int iPrice)
{
price=iPrice;
}
}
class orange{
int price;
public void myFunction(int iPrice)
{
price=iPrice;
}
}
public class main {
public static void main(String[] args) {
List <Object> list= new ArrayList<>();
//create 3 apple object to list
list.add( new apple() );
list.add( new apple() );
list.add( new orange() );
list.get(0). /* "get(0)." this isn't using apple object and my function */
}
}
解决方案
The method list.get(0)
returns an Object
reference, therefore you have to downcast cast it to apple
. Somewhat like this:
apple a = (apple)list.get(0);
And then call the function.
Note: It is a good practice that class names in Java be in capital letters like Apple
, Orange
这篇关于创建不同的对象的实例列表,并使用这些对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文