父构造函数调用的方法的行为与子方法相同 [英] Method called by parent constructor behaves as child method

查看:59
本文介绍了父构造函数调用的方法的行为与子方法相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试Java中的某些多态性,我的代码如下所示:

I am testing some polymorphism in java and my code looks like the following:

class Base {
        int value = 0;
        public Base(){
            System.out.println("Came Here And Value is: " + value);
            addValue();
        }
        String addValue(){
            System.out.println("Calling Bases' addValue and value is currently: " + value);
            value += 10;
            return "";
        }
        int getValue(){
            return value;
        }
}
class Derived extends Base{
        public Derived(){
            System.out.println("Calling Derived constructor and value currently is: " + value);
            addValue();
        }
        String addValue(){
            System.out.println("Came to Deriveds' addValue and value now is: " + value);
            value += 20;
            return "";
        }
        int getValue(){
            return value;
        }
}
public class MyClass {
    public static void main(String [] args){
       Base b = new Derived();
       System.out.println(b.getValue());

    }
}

所以这里的事情是,它可以打印40,但我想它应该可以打印30.我的想法是:new Derived首先调用new Base,后者调用 addValue()和(as addValue()的值加10)当时的值应为10.然后,将调用Derived的 addValue()使值变为30(因为Derived中定义的 addValue()会将值加20).但是,Base调用了它的孩子的 addValue().有人可以解释发生了什么事吗?

So the thing here is, it prints 40 but I'm guessing that it should print 30. My thoughts are: new Derived first calls new Base, which calls addValue() and (as addValue() defined in Base adds up value by 10) value should be 10 at that time. then, Derived's addValue() is called which makes value 30 (because addValue() defined in Derived adds value up by 20). But instead, Base invokes it's child's addValue(). Can someone explain what's happening?

推荐答案

您的思维过程中的误解以粗体显示:

The misconception in your thought process is bolded:

new Derived首先调用new Base,然后调用addValue()和(因为Base中定义的addValue()将值加10),此时值应为10.然后,Derived的addValue(),该值将变为30(因为在Derived中定义的addValue()将值加20).

new Derived first calls new Base, which calls addValue() and (as addValue() defined in Base adds up value by 10) value should be 10 at that time. then, Derived's addValue() is called which makes value 30 (because addValue() defined in Derived adds value up by 20).

尽管 addValue 放置在基类构造函数中,它仍在 this 上调用 addValue ,如下所示:

Although addValue is placed inside the base class constructor, it is still calling addValue on this, like this:

this.addValue();

那么, this 是什么?它是一个 Derived 类实例.派生类的 addValue 有什么作用?它增加了20.这就是为什么您有40.

Well, what is this? It is a Derived class instance. What does the derived class's addValue do? It adds 20. That's why you got 40.

这篇关于父构造函数调用的方法的行为与子方法相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆