简体   繁体   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);
    }
}

In above example the output is null.在上面的例子中,output 是 null。

Why was not the constructor called?为什么不调用构造函数?

Constructors don't have a return type.构造函数没有返回类型。 There shouldn't be void in your StaticFinalExample() method, if that's your constructor.如果那是你的构造函数,你的 StaticFinalExample() 方法中不应该有void

Avoid using class name as a method name, it's ambiguous.避免使用 class 名称作为方法名称,这是不明确的。 When we notice any name having same value as class, our mind reads as a class name not as actual usage (method name in your case).当我们注意到任何与 class 具有相同值的名称时,我们的想法会读作 class 名称而不是实际用法(您的情况下的方法名称)。

It's not a good practice.这不是一个好习惯。 It does not mean you can not use method name as class name, but you should avoid using same name.这并不意味着您不能使用方法名称作为 class 名称,但您应该避免使用相同的名称。

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

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