Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating instances by static field

Tags:

java

static

I have the following two classes:

public class A{
    private String s;
    public A(String s){
        this.s = s;
    }
}

public class B{
    private static final String STR = "String";

    public void doAction(){
        A a = new A(STR); //Does it look really wierd?
    }
}

I've never passed the static final field as a constructor parameter, so can it lead to potential bugs? Should we avoid it or we can do that if it seems concise.

like image 586
user3663882 Avatar asked Aug 24 '26 14:08

user3663882


1 Answers

I've never passed the static final field as a constructor parameter, so can it lead to potential bugs?

This cannot lead to a bug, because doAction is an instance method. All static fields with initializers will be initialized before the first instance method is called, so you are safe.

Should we avoid it or we can do that if it seems concise?

Using a static final field, which is effectively a String constant, inside an instance method, is а perfectly valid choice.

like image 136
Sergey Kalinichenko Avatar answered Aug 26 '26 04:08

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!