7

A non-static setter method can look like this:

private int var;

public void setVar(int var) {
  this.var = var;
}

And I can't find out how to solve that with a static method:

private static int var;

public static void setVar(int var) {
  // ???
}

One solution is to write myClass.var = var;. But that's ugly, because when I rename my class, I have to find and replace all occurrences. Another solution is to rename the parameter to v and write var = v;. For me this is ugly, too.

Is there really no way to solve this like in php self::var = var;?

3
  • 2
    When using a proper IDE, you can always do a Refactor Rename, which will change any explicit classname aswell. Commented Apr 7, 2014 at 8:44
  • 1
    If you use some refactoring solution when you rename your class it should take care of those references for you. Commented Apr 7, 2014 at 8:44
  • Due to the fact that the class field var is private, you never have to search somewhere else then in the class itself for references, when you rename you class without using a proper refactoring tool (like an IDE). Besides, how do you find all the imports in other types where you use the setter method setVar() if you do not use an IDE? I suggest you use an IDE and there should be no real problem out there. Commented Apr 7, 2014 at 8:56

4 Answers 4

2

Renaming the field variable is the most convenient way. Take a look on Android Code Style Guideline. They suggest to name all static fields like sVariable. It's not ugly and very understandable. So, it would be like this:

private static int sVar;

public static void setVar(int var) {
  sVar = var;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I don't know how other IDEs behave, but when I auto-create a setter-method for sVar with NetBeans, the method-name will be setsVar instead of setVar. Annoying.
@halloei not annoying for me, just to delete one char.
You can change this setting in that ide. Eclipse and Intellj have that option not sure about netbeans though. But it should be there.
1

It's not possible to do this things in other way than you know...........

myClass.var = var;
var = v;

only two way that already you know.......... Both are good ..no one is ugly you can use.......

if you will uses any IDE like eclipse that will take care whenever you will change name of class...........

Comments

1

We need to write as follows:

 ClassName.var=var;

Comments

1

Do it like this:

public class Example {

    private static int var;

    public static void setVar(int var) {
      Example.var = var;
    }
}

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.