创建不同对象的实例列表并使用这些对象 [英] Creating instance list of different objects and using these objects

查看:26
本文介绍了创建不同对象的实例列表并使用这些对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 代码:

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 */

}
}

推荐答案

list.get(0) 方法返回一个 Object 引用,因此你必须向下转型它到 apple.有点像这样:

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

然后调用函数.

注意:Java 中的类名最好使用大写字母,例如 AppleOrange

Note: It is a good practice that class names in Java be in capital letters like Apple, Orange

这篇关于创建不同对象的实例列表并使用这些对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆