0

I have a SampleClass with static field a and b and a static method init. To re-create SampleClass with new value for a and b, I use below syntax:

public class SampleClass{

    private static int b;
    private static int a;
    
    public static void init(int a, int b) {
        SampleClass.a = a; //line 7
        SampleClass.b = b; //line 8
    }
}

I actually feel awkward about line 7 and line 8. Is this acceptable or there are more correct ways to do this?

5
  • Could you explain why you feel awkward about them? Commented Jul 21, 2020 at 8:40
  • I feel awkward calling the SampleClass within the SampleClass. It does what I need to do but I am not sure if there is an effect using this convention Commented Jul 21, 2020 at 8:44
  • 2
    I'm not sure how to address you confusion because it's unclear but I can tell you that there's nothing inacceptable with the lines. Commented Jul 21, 2020 at 8:53
  • Thanks @akuzminykh! You're assurance is helpful enough :) Commented Jul 21, 2020 at 9:00
  • SampleClass.a = a; is the recommended way if the variable name conflicts. Commented Jul 21, 2020 at 9:30

2 Answers 2

1

Your syntax is not wrong.

For static attributes, you either use the syntax you have provided in your question, either you assign different names for your parameters (for code self-explanatory reasons). For instance:

public static void init(int newA, int newB) {
    SampleClass.a = newA;
    SampleClass.b = newB;
}
Sign up to request clarification or add additional context in comments.

4 Comments

It won't work because it will throw Cannot use this in a static context
I think you're basically ignoring the question and just dump information about setters.
You're right, I did a tremendous mistake. I didn't ignore his answer, but I wanted to clarify some aspects.
@DavidBuzatu Okay, well done. But now don't just edit your answer with an excuse and don't keep the wrong part. Just give it a small rework so it answers the OP's question without any noisy text.
0

Yes, it's acceptable. In fact if you generate a Setter method for a static field, the assign way will also be SampleClass.a = a.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.