Reputation: 313
I have an ArrayList of type Object that contains 6 objects of different classes:
questions = new ArrayList<>();
questions.add(new Question1());
questions.add(new Question2());
questions.add(new Question3());
questions.add(new Question4());
questions.add(new Question5());
Depending on questionNum variable I have to get the object's method, i.e. isAnswered() from the ArrayList.
Example of what I want:
for (int i = 0; i < 5; i++)
{
questionNum = i;
if ((Question<questionNum>)questions.get(questionNum).isAnswered())
{
Log.d("Answered", String.valueOf(questionNum));
}
}
What I am using right now:
else if (questionNum == 4 &&
((Question5)questions.get(questionNum)).isAnswered())
Any way to make it more elegant or should I go with interfaces or inheritance (doing Android project, so the every question class already inherits Fragment)?
Upvotes: 0
Views: 566
Reputation: 8348
You can have each Question class implement an interface:
public interface Question{
public boolean isAnswered();
}
public class Question1 implements Question{
public boolean isAnswered(){
//implementation
}
//other code
}
Then add these as Questions to the List
List<Question> questions = new ArrayList<Question>();
questions.add(new Question1());
Then you can get the Question from the List and call the appropriate method:
if ( questions.get(0).isAnswered() ){
}
Upvotes: 1
Reputation: 8345
i see three solutions here:
A. Add a typecaster along with each question on ArrayList like this:
questions = new ArrayList<>();
questions.add(new ArrayList<>(Arrays.asList(new Question1(), "Question1")));
questions.add(new ArrayList<>(Arrays.asList(new Question2(), "Question2")));
Then have a switch
statement depending on the second type argument and type cast (literally) as needed
B. Have each Question*
class have a property type
and then use a switch
statement (as previously) to typecast appropriately, i.e:
class Question1
{
public String type = "Question1";
// ...
}
// ...
C. Have all Question*
classes inherit from common Question
superclass or implement common interface as needed, i.e:
class Question
{
public String type = "Question";
public Boolean isAnswered()
{
return false;
}
// ...
}
class Question1 extends Question
{
public String type = "Question1";
public Boolean isAnswered()
{
// ..
}
// ...
}
// ..
Upvotes: 0