为什么没有为此Java程序调用构造函数

问题描述 投票:0回答:4

我正在尝试了解代码的调用顺序。不知道我的方法是否错误或是否存在其他问题,但是不知道如何调用类构造函数。程序的其余部分正在成功执行。有人,请说明通话顺序。

public class MainWithStaticCalls
{
    static
    {
        String[] str = {"1", "2"};
        System.out.println("Static");
        main(str);
    }
    {
        System.out.println("Init block");
    }
    void MainWithStaticCalls()
    {
        System.out.println("constructor");
    }
    public static void main(String[] a)
    {
        MainWithStaticCalls obj = new MainWithStaticCalls();
        NewClass nc = new NewClass();
        nc.callMe();
        System.out.println("Main");
    }

}

class NewClass
{
    public void callMe()
    {
        System.out.println("I'm called");
    }
}

据我了解,一旦JVM开始执行,甚至在主类之前,静态块就会立即执行。然后实例init块将被执行。那么构造函数应该被执行,但是不知何故没有执行。因此,如果有人可以解释它为什么会这样,那将是一个很大的帮助。

My output:
Static
Init block
I'm called
Main
Init block
I'm called
Main
java java-8 constructor
4个回答
1
投票

类中没有定义构造函数,因此将调用默认构造函数。

void MainWithStaticCalls()

不是构造函数。这是方法,因为构造函数没有返回类型。


0
投票

void MainWithStaticCalls()是一种方法,而不是构造函数。

更改为,

public MainWithStaticCalls()
{
   System.out.println("constructor");
}

有为构造函数定义的规则。

  1. 构造函数名称必须与它的类名称相同
  2. 构造函数必须没有显式的返回类型
  3. Java构造函数不能是抽象的,静态的,最终的和同步的

0
投票

在Java中,构造函数不是方法。它仅具有类的名称和特定的可见性。如果它声明返回某个内容,则它不是构造函数,即使声明返回一个void也不是。


0
投票

正如其他人已经提到的那样,您将构造函数与方法混淆了。删除“ void”使其再次成为构造函数。仅供参考-这是oracle docs中描述的构造方法:https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

© www.soinside.com 2019 - 2024. All rights reserved.