gpt4 book ai didi

java - Java构造函数是方法吗?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:13:35 24 4
gpt4 key购买 nike

这个问题真让人费解

________ 是一个特殊方法,它与类同名,并且在实例化类的对象时自动调用。答案:

  • 构造函数

  • 二传手

  • setter/getter

  • 静态方法

我在想构造函数是唯一与类同名的类,但是等等!构造函数并不是真正的方法,它与方法不同。所以我读了this文章得出的结论是这个问题格式错误,我是对的吗?

最佳答案

Constructors 实际上是一种特殊的方法,用于初始化新创建的实例的状态。当您创建一个实例时:-

A obj= new A();

然后,使用 new 关键字创建类 A 的实例,然后在新创建的实例上调用构造函数 A()

进一步从那篇文章说:-

Constructors have one purpose in life: to create an instance of a class.

不,这是错误的。构造函数不创建实例,它是 new 关键字。然后构造函数初始化如上所述创建的实例的状态。

来自 JLS - Section 8.8 :-

Constructors are invoked by class instance creation expressions (§15.9), by the conversions and concatenations caused by the string concatenation operator + (§15.18.1), and by explicit constructor invocations from other constructors (§8.8.7).

Constructors are never invoked by method invocation expressions (§15.12).

同样来自 oracle tutorial

Point originOne = new Point(23, 94);

The above statement has three parts (discussed in detail below):

Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
Instantiation: The new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

关于java - Java构造函数是方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12987361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com