Does invoking a constructor mean creating object?

前端 未结 8 1484
情书的邮戳
情书的邮戳 2020-12-06 05:26

When we create a Subclass object which extends an abstract class, the abstract class constructor also runs . But we know we cannot create objects of an abstract class. Hence

相关标签:
8条回答
  • 2020-12-06 05:59

    When you invoke a constructor using new, a new object is being created.

    Now, as you probably already know, every constructor of any subclass, either implicitly or explicitly, directly or indirectly, invokes a constructor from the parent class (which, in turns, invokes one from its own parent class, all the way up to object). This is called constructor chaining.

    The above, however doesn't mean that multiple objects are created. The object has been created at the new call and all constructors working on that object are already handed an allocated area. Therefore, constructor chaining does not create new objects. One call to new will return you one object.

    0 讨论(0)
  • 2020-12-06 06:00

    But we know we cannot create objects of an Abstract class

    Right but JVM can.

    does it mean that even if a constructor completes running without any exception , there is no guarantee whether an object is created ?

    The object is definitely created internally.

    Does invoking a constructor mean creating object?

    Not always. you can invoke constructor using super() and this() but it won't instantiate an object. (but will just invoke the constructor)

    class AClass
    {
        AClass()
        {
            this(1); // will invoke constructor, but no object instatiated.
        }
    
        AClass(int a)
        {
    
        }
    
        public static void main(String[] args)
        {
            AClass obj = new AClass(); // one object instantiated.
        }
    }
    
    0 讨论(0)
提交回复
热议问题