Is it posible to store functions in an array in java?
Like for example..
public void getMyname(){
// do something here;
}
public void getLastname(){
//do something here;
}
Array arr = {getLastName,getMyname};
Like that? if so is it right?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can’t store methods in arrays in Java, because methods aren’t first-class objects in Java. It’s a reason some people prefer to use other languages like Python, Scheme, etc.
The work-around is to create an interface which contains one method, then create four classes implementing that interface – the MoveRight, MoveLeft, etc… classes. Then you can store instances of those classes in your array and call them all the same way.