[英]Java/Android - GettingClassCast exception casting a base class to a subclass to invoke the subclass methods
因此,我有一個GeneralTemplate類和一個擴展GeneralTemplate的Exercise類。
從我包含的GeneralTemplate代碼中可以看出,擴展它的每個類(有幾個類)都包含一個ArrayList
當我到達這條線...
Exercise chosenExercise = (Exercise) FitnessApp.routineList.get(chosenRoutinePosition).getItem(chosenWorkoutPosition).getItem(chosenExercisePosition);
我收到以下錯誤ClassCastExceptionjava.lang.ClassCastException: com.karibastudios.gymtemplates.GeneralTemplate cannot be cast to com.karibastudios.gymtemplates.Exercise
我不明白為什么會這樣,因為Exercise是GeneralTemplate的子類?
GeneralTemplate代碼:
public class GeneralTemplate
{
private String name;
private ArrayList <GeneralTemplate> items; // Generic items list
// Super constructor for all subclasses
public GeneralTemplate(String name)
{
this.setName(name);
items = new ArrayList<GeneralTemplate>();
}
// Only sets will differ
public void addItem(String newName)
{
items.add(new GeneralTemplate(newName));
}
// Remove item at position
public void removeItem(int position)
{
if (items.size() > 0 && position <= items.size())
items.remove(position);
}
// Remove all items
public void removeItems()
{
items.clear();
}
/* ****************** GETTERS AND SETTERS START ********************/
// Get item
public GeneralTemplate getItem(int position)
{
return items.get(position);
}
// Set list of objects e.g Routines, Workouts, Exercises
public void setItems(ArrayList <GeneralTemplate> items)
{
this.items = items;
}
// Return item list
public ArrayList <GeneralTemplate> getItems()
{
return items;
}
// Return name
public String getName()
{
return name;
}
// Set name
public void setName(String name)
{
this.name = name;
}
/* ****************** GETTERS AND SETTERS END ********************/
}
嘗試強制轉換GeneralTemplate行使以調用方法的異常代碼
chosenRoutinePosition = getIntent().getIntExtra("chosen_routine", 0);
chosenWorkoutPosition = getIntent().getIntExtra("chosen_workout", 0);
chosenExercisePosition = getIntent().getIntExtra("chosen_workout", 0);
// Navigates through the Routine List and gets the chosen routine
chosenExercise = (Exercise)FitnessApp.routineList.get(chosenRoutinePosition).getItem(chosenWorkoutPosition).getItem(chosenExercisePosition);
Exercise類非常簡單,並使用其他一些方法擴展了GeneralTemplate
這是一個絆腳石,任何幫助都將是驚人的。
干杯
ClassCastExceptionjava.lang.ClassCastException: com.karibastudios.gymtemplates.GeneralTemplate cannot be cast to com.karibastudios.gymtemplates.Exercise
在Java中,您只能沿一個方向進行投射。 例如:ListView是一個View,但並非所有View都是ListView(它可以是Button,RelativeLayout等)。
因此,您可以從“練習”轉到“ GeneralTemplate”,但不能相反。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.