Class.newInstance()如何使用方法?

时间:2013-03-14 18:40:12

标签: java class abstract-class

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

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()'方法。

我该怎么做?

2 个答案:

答案 0 :(得分:6)

你可以简单地施展它:

Chance obj = (Chance) aClass.newInstance();
double d = obj.getChance();

答案 1 :(得分:3)

没有施法:

Class<? extends Chance> aClass = Class.forName(chanceClass....).asSubclass(Chance.class); 
Chance obj = aClass.newInstance();
double d = obj.getChance();