Does an instance of superclass get created when we instantiate an object?

前端 未结 3 646
旧巷少年郎
旧巷少年郎 2020-12-01 15:01

Does an instance of superclass get created when we instantiate a particular class in java. If that is the case then there would be a lot of overhead of instantiating all the

3条回答
  •  庸人自扰
    2020-12-01 15:39

    Yes.

    BClass constructor looks like this:

    public BClass ()
    {
        super (); // hidden line, added by compiler
        System.out.println("Constructor B");
    }
    

    If you do not want to use default constructor, you can do like this:

    public BClass ()
    {
        super (parameters); // now you will use different constructor from AClass
                            // compiler will not add here call to "super ()"
        System.out.println("Constructor B");
    }
    

    From oracle site: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

提交回复
热议问题