子类构造函数(JAVA)中的重写函数 [英] Overridden Function within Child Class Constructor (JAVA)

查看:35
本文介绍了子类构造函数(JAVA)中的重写函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在派生类构造函数中调用超类构造函数时,id = 0的值为何?创建子对象时,何时在堆中为该对象分配内存?在基类构造函数运行之后还是之前?

Why is the value of id = 0 when super class constructor is called within the derived class constructor? When child object is created, when is memory allotted in the heap for the object? After the base class constructor runs or before?

class Parent{
        int id = 10;
        Parent(){
            meth();
        }
        void meth(){
            System.out.println("Parent :"+ id);
        }
    }
    class Child extends Parent{
        int id = 5;
        Child(){
            meth();
        }
        void meth(){
            System.out.println("Child :"+ id);
        }
    }
    public class OverRidingEg {

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Child a= new Child();

        }

    }

推荐答案

首先执行超类构造函数.因此,当调用重写方法时,子构造函数尚未执行,因此子类中的 id 字段仍具有其默认值.

The superclass constructor is executed first. So when the overridden method is called, the child constructor hasn't been executed yet, so id field in the subclass still has its default value.

这就是为什么从构造函数中调用可重写方法的做法不好,并被PMD之类的工具标记出来的原因:调用此类方法时,对象的不变性无法实现.

That's why calling overridable methods from a constructor is a bad practice, flagged by tools such as PMD: the invariants of the objects are not fulfilled when such a method is called.

这篇关于子类构造函数(JAVA)中的重写函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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