Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java static self-references

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;?

like image 899
halloei Avatar asked Apr 07 '14 08:04

halloei


People also ask

How do you reference static in Java?

To create a static method in Java, you prefix the key word 'static' before the name of the method. A static method belongs to the class, and you do not have to create an instance of the class to access the static method. Referring to the dress analogy, a static method would get its design from the original dress.

Can a object reference be static in Java?

An object reference cannot be static. Static-ness is not a meaningful property for object references. It simply doesn't make sense. An object reference is a value, not a variable.

What is static referencing?

A static reference is reference that exists only once for an entire class. No matter how many instances of that class exist there is only one that one reference.


4 Answers

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;
}
like image 95
nikis Avatar answered Oct 19 '22 18:10

nikis


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...........

like image 1
Kuldeep Choudhary Avatar answered Oct 19 '22 17:10

Kuldeep Choudhary


We need to write as follows:

 ClassName.var=var;
like image 1
lab bhattacharjee Avatar answered Oct 19 '22 17:10

lab bhattacharjee


Do it like this:

public class Example {

    private static int var;

    public static void setVar(int var) {
      Example.var = var;
    }
}
like image 1
Harmlezz Avatar answered Oct 19 '22 17:10

Harmlezz