gpt4 book ai didi

java - 为什么不能像函数一样调用构造函数?

转载 作者:行者123 更新时间:2023-11-29 07:48:55 25 4
gpt4 key购买 nike

以下代码不起作用,因为编译器说函数 AnotherNewClass() 不存在?这是为什么?构造函数不只是一个函数吗?为什么构造函数不能在不引用特定对象的情况下运行?

class AnotherNewClass
{

public AnotherNewClass(){
System.out.println("Hello World!!");
}

public AnotherNewClass(String arg){
System.out.println("Hello World!!");
}


public static void main(String []args){
AnotherNewClass("Hello World!!");//This is the offending code; where the compiler throws an error
}

}

附言。从下面的一些评论中,我想澄清一下,我明白我没有使用 new 关键字,这个问题的目的是强调函数和构造函数之间的区别(如果没有 'new' 就不能调用它)

最佳答案

可以,但是您需要 new 关键字。

new AnotherNewClass("Hello World!!");

请注意,这不仅仅是调用构造函数。这正是您需要 new 关键字的原因。 new 关键字将在堆上分配内存,您的类的对象可以放入其中。但是该内存还不包含这样的对象。然后构造函数初始化那 block 内存。这就是为什么您不想将构造函数用作常规函数的原因。

关于java - 为什么不能像函数一样调用构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22888042/

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