如何从子类调用方法?

问题描述 投票:0回答:1

所以我有一个项目,其中我有一个特定的问题,如果我们正确回答它,就会得到一定数量的分数,该分数根据问题的主题而变化。我有一个名为 Pergunta(Question) 的类,其中包含不同主题的子类,例如 PerguntasArtes(ArtQuestions),我想在每个子类中编写一个方法来进行积分计算。


public class Pergunta {
    private String area;
    private String pergunta;
    private ArrayList<String> opcoes;
    private String respostaCorreta;
    private String dificuldade;
    protected int pontosPergunta;

    public Pergunta(String area, String pergunta, ArrayList<String> opcoes, String respostaCorreta, String dificuldade, int pontosPergunta) {
        this.area = area;
        this.pergunta = pergunta;
        this.opcoes = opcoes;
        this.respostaCorreta = respostaCorreta;
        this.dificuldade = dificuldade;
        this.pontosPergunta = pontosPergunta;

    }

    public static Pergunta readFromFile(String filename) {
        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split("-");
                String area = parts[0];
                String dificuldade = parts[1];
                String pergunta = parts[2];
                ArrayList<String> opcoes = new ArrayList<>(Arrays.asList(parts[3].split(",")));
                String respostaCorreta = parts[4];
                int pontosPergunta = Integer.parseInt(parts[5]);
                return new Pergunta(area, pergunta, opcoes, respostaCorreta, dificuldade, pontosPergunta);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getPergunta() {
        return pergunta;
    }

    public ArrayList<String> getOpcoes() {
        return opcoes;
    }

    public void setArea(String area){
        this.area=area;
    }
    public String getArea(){
        return this.area;
    }
public class PerguntaArtes extends Pergunta {
    public PerguntaArtes(String area, String pergunta, ArrayList<String> opcoes, String respostaCorreta, String dificuldade, int pontosPergunta) {
        super(area, pergunta, opcoes, respostaCorreta, dificuldade, pontosPergunta);
    }

    public int calcularPontuacao(){
        return pontosPergunta * 10;
    }
}

以下方法是检查我的答案是否正确,我需要它从子类调用该方法

private void checkAnswer(String selectedOption, String respostaCorreta, Pergunta pergunta){
        if (selectedOption.equals(respostaCorreta)){
            if (pergunta.getArea().equals("PerguntaArtes")){
                PerguntaArtes PerguntaArtes = (PerguntaArtes) pergunta;
                score += PerguntaArtes.calcularPontuacao();
            }
            if (pergunta.getArea().equals("PerguntaCiencias")){
                score += 20;
            }
            if (pergunta.getArea().equals("PerguntaDesporto")){
                score += 20;
            }
            questionnumber += 1;
            if (questionnumber <= 5){
                displayQuestion(questionnumber);
            }
            else {
                endGame();
            }
        }
        else {
            questionnumber += 1;
            if (questionnumber <= 5){
                displayQuestion(questionnumber);
            }
            else {
                endGame();
            }
        }
    }

在这种情况下,它给了我以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: class Pergunta cannot be cast to class PerguntaArtes (Pergunta and PerguntaArtes are in unnamed module of loader 'app')
        at Screen.checkAnswer(Screen.java:164)
        at Screen$2.actionPerformed(Screen.java:142)
        at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
        at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
        at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405)
        at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
        at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
        at java.desktop/java.awt.Component.processMouseEvent(Component.java:6626)
        at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3389)
        at java.desktop/java.awt.Component.processEvent(Component.java:6391)
        at java.desktop/java.awt.Container.processEvent(Container.java:2266)
        at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
        at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
        at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
        at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
        at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4575)
        at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
        at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
        at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
        at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
        at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:775)
        at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:720)
        at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:714)
        at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
        at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
        at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
        at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:747)
        at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
        at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
        at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
        at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:744)
        at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
        at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
        at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
        at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
        at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
        at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

我也尝试过其他方法,但没有找到解决办法。 我也不能使用instanceof或class.getName(),因为如果我使用它我就会受到惩罚。 你们能帮我吗?

java class methods subclass
1个回答
0
投票

您可以:

  • 使您的“Pergunta”类抽象并创建一个名为“calcularPontuacao”的方法
public abstract class Pergunta {
    public abstract int calcularPontuacao(); 
}

然后在你的子方法上重写它

public class PerguntaArtes extends Pergunta{
    @Override
    public int calcularPontuacao() {
        return pontosPergunta * 10;
    }
}

public class PerguntaScience extends Pergunta{
    @Override
    public int calcularPontuacao() {
        return pontosPergunta * 20;
    }
}
  • 使用名为“calcularPontuacao”的方法创建一个接口
public interface PuntuationRegister {
    int calcularPontucao();
}

public class PerguntaArtes implements PuntuationRegister{
    @Override
    public int calcularPontuacao() {
        return pontosPergunta * 10;
    }
}

我还建议您在这部分使用 .equalsIgnoreCase 或枚举

if (pergunta.getArea().equals("PerguntaArtes"))

© www.soinside.com 2019 - 2024. All rights reserved.