简体   繁体   中英

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.

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.

Avoid using class name as a method name, it's ambiguous. 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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