Accessing a function of an instance which is in an arraylist
Posted
by
fadeir
on Stack Overflow
See other posts from Stack Overflow
or by fadeir
Published on 2012-06-17T20:52:25Z
Indexed on
2012/06/17
21:16 UTC
Read the original article
Hit count: 160
I'm tring to access a function of an instance which is in an arraylist. Is there any way to do that without using the class name of the instance?
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 list= new ArrayList();
//create 3 apple object to list
list.add( new apple() );
list.add( new apple() );
list.add( new orange() );
list.get(0).myFunction(1); /* Error: The method myFunction(int) is undefined for the type Object*/
}
}
I know that;((apple) list.get(0)).myFunction(1);
is a way but I'dont want to use any class name while calling the function.
© Stack Overflow or respective owner