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

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

问题描述

当我们创建一个扩展抽象类的子类对象时,抽象类构造函数也会运行。但是我们知道我们不能创建一个抽象类的对象。因此,这意味着即使构造函数完成运行时没有任何异常,也不能保证是否创建了对象。

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 c $ c> 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 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.

查看

  • Creation of new Class Instance - JLS-Section#12.5

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

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