繁体   English   中英

在 Java 中创建 object 时未调用默认构造函数

[英]Default Constructor not called while creating object in Java

public class StaticFinalExample {
    static String str;

    public void StaticFinalExample() {
        System.out.println("In Constr");
        str = "H";
    }

    public static void main(String[] args) {
        StaticFinalExample t = new StaticFinalExample();
        System.out.println(str);
    }
}

在上面的例子中,output 是 null。

为什么不调用构造函数?

构造函数没有返回类型。 如果那是你的构造函数,你的 StaticFinalExample() 方法中不应该有void

避免使用 class 名称作为方法名称,这是不明确的。 当我们注意到任何与 class 具有相同值的名称时,我们的想法会读作 class 名称而不是实际用法(您的情况下的方法名称)。

这不是一个好习惯。 这并不意味着您不能使用方法名称作为 class 名称,但您应该避免使用相同的名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM