I have the following implementation that gives a compiler error:
public enum FusionStat implements MonsterStatBuilderHelper {
ATTACK {
@Override
public MonsterCard.MonsterCardBuilder safeCreateBuilder(final MonsterCard baseMonsterCard, final MonsterCard fusedMonsterCard, final FusionCard fusionCard) {
Objects.requireNonNull(baseMonsterCard);
Objects.requireNonNull(fusedMonsterCard);
Objects.requireNonNull(fusionCard);
if (baseMonsterCard.equals(fusedMonsterCard)) {
throw new IllegalArgumentException("baseMonsterCard and fusedMonsterCard need to be different");
}
return new MonsterCard.MonsterCardBuilder(baseMonsterCard)
.attack(baseMonsterCard.getAttack() + (fusionCard.getFusionPower() * fusedMonsterCard.getAttack()));
}
},
HITPOINTS {
@Override
public MonsterCard.MonsterCardBuilder safeCreateBuilder(final MonsterCard baseMonsterCard, final MonsterCard fusedMonsterCard, final FusionCard fusionCard) {
Objects.requireNonNull(baseMonsterCard);
Objects.requireNonNull(fusedMonsterCard);
Objects.requireNonNull(fusionCard);
if (baseMonsterCard.equals(fusedMonsterCard)) {
throw new IllegalArgumentException("baseMonsterCard and fusedMonsterCard need to be different");
}
return new MonsterCard.MonsterCardBuilder(baseMonsterCard)
.maximumHitpoints((int)(baseMonsterCard.getMaximumHitpoints() + (fusionCard.getFusionPower() / 100d * fusedMonsterCard.getMaximumHitpoints())))
.hitpoints((int)(baseMonsterCard.getHitpoints() + (fusionCard.getFusionPower() / 100d * fusedMonsterCard.getHitpoints())));
}
};
protected interface MonsterStatBuilderHelper extends MonsterStatBuilder {
default MonsterCard.MonsterCardBuilder safeCreateBuilder(final MonsterCard baseMonsterCard, final MonsterCard fusedMonsterCard, final FusionCard fusionCard) {
return createBuilder(baseMonsterCard, fusedMonsterCard, fusionCard);
}
}
}
@FunctionalInterface
interface MonsterStatBuilder {
MonsterCard.MonsterCardBuilder createBuilder(final MonsterCard baseMonsterCard, final MonsterCard fusedMonsterCard, final FusionCard fusionCard);
}
It gives a cyclic inheritance error on the first line involving FusionStat
.
I don't exactly see what is going on. I had first implemented an abstract class and wanted to let the enum extend that, until I realized that enums cannot extend classes. Now I try to (ab)use the default methods in Java 8.
I am interested in the thought process about why my code does not compile, I was trying to remove code duplication (still have to do so), by pulling the duplicated code inside safeCreateBuilder
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…