0

我创建了一个抽象类,如下所示:

abstract class Chance
{

   public void setTeams(SportEvent aSportEvent)
   {
      firstTeam = aSportEvent.getFirstTeam();
      secondTeam = aSportEvent.getSecondTeam();
   }


   private int totalPlayedGames()
   {
      int playedAtHome = firstTeam.getHomePlayedGames();
      int playedAway = secondTeam.getAwayPlayedGames();
      int playedGames = playedAtHome + playedAway; 
      return playedGames;
   }


   private int totalScoredGoals()
   {
      int homeScoredGoals = firstTeam.getHomeScoredGoals();
      int awayScoredGoals = secondTeam.getAwayScoredGoals();
      int scoredGoals = homeScoredGoals + awayScoredGoals; 
      return scoredGoals;
   }

   abstract double getChance()

   Team firstTeam;
   Team secondTeam; 
}

然后,当然,我有几个类的方法getChance()......

现在,我想创建一个类,我可以在其中获得getChance()这些新类的结果。我想使用类似的东西:

Class aClass = Class.forName(chanceClass....);
Object obj = aClass.newInstance();

现在我想使用'getChance()'方法。

我该怎么做?

4

2 回答 2

6

您可以简单地转换它:

Chance obj = (Chance) aClass.newInstance();
double d = obj.getChance();
于 2013-03-14T18:41:27.380 回答
3

没有铸造:

Class<? extends Chance> aClass = Class.forName(chanceClass....).asSubclass(Chance.class); 
Chance obj = aClass.newInstance();
double d = obj.getChance();
于 2013-03-14T18:45:46.260 回答