父类正在从子类调用方法

父类正在从子类调用方法

本文介绍了Java - 父类正在从子类调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,我对编码还是个新手,可能没有掌握所有术语.希望你仍然能理解我的问题.我想得到的输出是:

Sorry, I am still new to coding and may not have all the terminologies down. Hopefully, you will still understand my question. The output that I want to get is:

"Cost for Parent is: 77.77"
"Cost for Child is: 33.33"

但是,我得到了这个:

"Cost for Parent is: 33.33"
"Cost for Child is: 33.33"

谁能理解为什么?我在下面有一个简化版本的代码,但其背后的逻辑保持不变......

Can anyone understand why? I have a simplified version of my code below but kept the logic behind it the same...

public class Parent{
    public double calculateCost(){
        return 77.77;
    }

    @Override
    public String toString(){
        return "Cost for Parent is: " + calculateCost();
    }
}

public class Child extends Parent{
    @Override
    public double calculateCost(){
        return 33.33;
    }

    @Override
    public String toString(){
        return super.toString() + "\nCost for Child is: " + calculateCost();
    }

    public static void main(String[] args){
        Child child1 = new Child();
        System.out.println(child1.toString());
    }
}

在我看来,Child 类中的 toString() 应该调用 Parent 类中的 toString()(因此,Parent 类中的 calculateCost())然后使用 Child 中的 calculateCost() 添加到它.我猜 super.toString() 中的 super 不适用于它包含的 calculateCost() .

In my mind, the toString() in the Child class should be calling the toString() from the Parent class (thus, the calculateCost() from Parent class) then adding to it with a calculateCost() from Child. I'm guessing the super in super.toString() does not apply to calculateCost() that it contains.

另外,我知道我可以通过在 Child 类中编写 toString() 来解决这个问题:

Also, I know I can get around it by writing the toString() in the Child class like this:

    @Override
    public String toString(){
        return "Cost for Parent is: " + super.calculateCost() + "\nCost for Child is: " + calculateCost();
    }

但重点是我不想重复代码,我宁愿添加到我要覆盖的前一个 toString() 方法中.请帮助或指导我(不知道我应该在谷歌上搜索什么......)谢谢!

but the point is that I don't want to repeat code and that I'd rather add to the previous toString() method that I am overriding. Please help or direct me (not sure what I should be googling for...) Thanks!

推荐答案

calculateCostChild 类中被覆盖.因此,当从 Child 调用 super.toString() 时,super.toString() 中的 calculateCost()code> 将是 ChildcalculateCost.

calculateCost is overriden in the Child class. Therefore when super.toString() is called from the Child, the calculateCost() in the super.toString() would be the Child's calculateCost.

您必须将 super.calculateCost() 明确地放在 Child 类中以调用 ParentcalculateCost.

You have to put super.calculateCost() explicitly in the Child class to call the Parent's calculateCost.

这篇关于Java - 父类正在从子类调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 12:04