• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList with polymorphism and inheriting it to another class..

 
Joseph Cho
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have one class that holds an ArrayList of an abstract class. Two different classes extend this abstract class. I fill the array with either one or the other of the two. The problem is, in an outside class when I set a reference to the object that contains the class holding the ArrayList, I cant access any instance variables from it.

If I check the ArrayList's size the size is holding the correct value, but displays null when I print out a value..

Ex:

System.out.println(questionPanel.questions.get(0).answer);
gives me null.. but it holds a value..
but

System.out.println(questionPanel.questions.size());
shows 3..

How do I access the values out of the ArrayList from another class properly?

Thanks!
 
Winston Gutkowski
Bartender
Pie
Posts: 10508
64
Eclipse IDE Hibernate Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joseph Cho wrote:System.out.println(questionPanel.questions.get(0).answer);
gives me null.. but it holds a value..

Well that sounds right; otherwise the .answer bit would have thrown NullPointerException.

How do I access the values out of the ArrayList from another class properly?

Exactly as you are doing; it doesn't sound to me like that's your problem. The fact is that answer is null, not the ArrayList entry.

However, one tip I would give you is that stringing lots of derefs ('.') together can make things difficult to follow, so why not just break them up? viz:It may seem like a lot more code, but it'll help an awful lot in debugging.

HIH

Winston
 
Joseph Cho
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the response Winston; I tried it the way you suggested and I still get a null print.. Guess I will just have to keep playing around with it.

 
Joseph Cho
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gosh dang it..

I found the issue..

Question(String question, String Answer)
{
this.question = question;
this.answer = answer;
}

inside the constructor, I capitalize a in answer .. doh!

Thanks for the help heh though and at least I gained some knowledge from you still.

Thanks again!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic