调用构造函数是否意味着创建对象? [英] Does invoking a constructor mean creating object?

查看:36
本文介绍了调用构造函数是否意味着创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们创建一个扩展抽象类的子类对象时,抽象类构造函数也会运行.但是我们知道我们不能创建抽象类的对象.那么是不是意味着即使构造函数无异常运行完成,也不能保证是否创建了对象?

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 does it mean that even if a constructor completes running without any exception, there is no guarantee whether an object is created?

推荐答案

因此这是否意味着即使构造函数完成运行无一例外,不能保证一个对象是否是创建?

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

简单地说,构造函数不会创建对象.它只是初始化对象的状态.创建对象的是 new 操作符.现在,让我们稍微详细地了解一下.

Simply speaking, a constructor does not create an object. It just initializes the state of the object. It's the new operator which creates the object. Now, let's understand this in little detail.

当你使用这样的语句创建一个对象时:

When you create an object using statement like this:

new MyClass();

对象首先由 new 操作符创建.就在对新创建对象的引用作为结果返回之前,处理指示的构造函数以初始化新对象.

The object is first created by the new operator. Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object.

现在考虑抽象类的情况,它是具体的SubClass,当你这样做时:

Now consider the case of Abstract class and it's concrete SubClass, when you do like this:

AbstractClass obj = new ConcreteClass();

new 操作符创建一个ConcreteClass 的对象,并调用其构造函数来初始化所创建对象的状态.在这个过程中,抽象类的构造函数也是从ConcreteClass构造函数中调用的,对抽象类中对象的状态进行初始化.

new operator creates an object of ConcreteClass, and invokes its constructor to initialize the state of the created object. In this process, the constructor of the abstract class is also called from the ConcreteClass constructor, to initialize the state of the object in the abstract class.

所以,基本上没有创建AbstractClass 的对象.只是调用了它的构造函数来初始化对象的状态.

So, basically the object of AbstractClass is not created. It's just that it's constructor is invoked to initialize the state of the object.

经验教训:

  • 对象是由 new 操作符创建的,而不是由构造函数本身的调用创建的.因此,对象在调用任何构造函数之前已经创建.

  • The object is created by new operator, and not by the invocation of the constructor itself. So, the object is already created before any constructor is invoked.

Constructor 只是用来初始化所创建对象的状态.它本身不创建对象.

Constructor is just used to initialize the state of the object created. It does not create an object itself.

对象状态也可以包含在抽象超类中.

An object state can also be contained in an abstract super class.

见:

这篇关于调用构造函数是否意味着创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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