user3663882
user3663882

Reputation: 7357

Creating instances by static field

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.

Upvotes: 3

Views: 82

Answers (3)

jungyh0218
jungyh0218

Reputation: 568

String is a reference type, but it works like a primitive type sometimes. If you use a String object as an argument, it will be copied, like other primitive variables. I don't understand the reason you pass a class variable as an argument of other object. But it will not occur any problem caused by sharing of an attribute between objects of this class.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

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.

Upvotes: 7

ka4eli
ka4eli

Reputation: 5424

You shouldn't worry if the field is immutable (like in your case: String is immutable data structure). With mutable objects (for example arrays) you should consider that all changes to this field in one object will be visible to other objects with the same field whether it is static or not. These code doesn't look weird.

Upvotes: 3

Related Questions