Handling Class Cast Exception Correctly in Java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • isaacsanya01
    New Member
    • Nov 2012
    • 6

    Handling Class Cast Exception Correctly in Java

    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.
    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
    								}
    	}
    	}
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    I don't know Java but I know that anyone that can help you will need more information. Like the class definitions.

    Comment

    • isaacsanya01
      New Member
      • Nov 2012
      • 6

      #3
      hi rabbit, thanks for the response, class definitions of what exactly?
      Code:
      public class SpecificUserPreference extends UserPreference
      Code:
      public class HighLevelUserPreference extends UserPreference
      the extend keyword is used to denote an inheritance relationship between parent class userpreference and its respective relationship with child class specific user preference and high level specific user preference. i just need to know how to cast correctly i suppose.

      Comment

      Working...