Hello,
I have a parent class called UserPreference. This class is composed of 2 child classes namely HighLevelUserPr eference and SpecificUserPre ference. Please, could you tell me whats wrong with the code below as I keep getting a class cast exception. I have used the instanceOf function to check the object type before casting. However, this doesn't seem to work. the error i am getting says: 'Exception in thread "main" java.lang.Class CastException: HighLevelUserPr eference cannot be cast to SpecificUserPre ference.' i can get either a highlevel or specifc user preference, i want to be able to handle both situations. I would have thought the code below is sufficient enough but i suppose i am missing something... thanks.
I have a parent class called UserPreference. This class is composed of 2 child classes namely HighLevelUserPr eference and SpecificUserPre ference. Please, could you tell me whats wrong with the code below as I keep getting a class cast exception. I have used the instanceOf function to check the object type before casting. However, this doesn't seem to work. the error i am getting says: 'Exception in thread "main" java.lang.Class CastException: HighLevelUserPr eference cannot be cast to SpecificUserPre ference.' i can get either a highlevel or specifc user preference, i want to be able to handle both situations. I would have thought the code below is sufficient enough but i suppose i am missing something... thanks.
Code:
if (userPreferences != null)
{
for (Iterator userPrefiterator = userPreferences.iterator(); userPrefiterator.hasNext();)
{
HighLevelUserPreference highUserPref = new HighLevelUserPreference();
SpecificUserPreference specificUserPref = new SpecificUserPreference();
if (highUserPref instanceof UserPreference) // determines type of object
{
highUserPref = (HighLevelUserPreference) userPrefiterator.next();
// do something
}
else
if (specificUserPref instanceof UserPreference)
{
specificUserPref = (SpecificUserPreference) userPrefiterator.next();
// do something
}
}
}
Comment