0

So let's say I have this code for a class:

public class A { static int myInt; static void setMyInt(int myInt) { // ... } } 

I don't know why you would have a setter in a static method, but this is just an example. Normally for a non-static situation, I would do something like this:

public class A { int myInt; void setMyInt(int myInt) { this.myInt = myInt; } } 

Using this accesses the field instead of the parameter. However, in the static method, I can't access this since it is a non-static field. How do I go about accessing the field from a static method?

1
  • You can access a static field from a static method without this. You cannot access a non-static field from a static method, unless you first create an instance and access that instance's field. You can return the instance from the static method, so that the caller can see the set instance field. Commented Apr 24, 2020 at 4:20

2 Answers 2

2

Because it is static, there is no this. Option 1: Give the parameter another name. Option 2: Use the class name to specify which myInt. Like,

static int myInt; static void setMyInt(int myInt) { A.myInt = myInt; } 

or

static int myInt; static void setMyInt(int myOtherInt) { myInt = myOtherInt; // A.myInt = myOtherInt; would also work } 
Sign up to request clarification or add additional context in comments.

Comments

1

when you define static property you no need create instance from your class . for non-static property and encapsulation using setter for each field is better and by this keyword can give value to Intended property.

 int myInt; void setMyInt(int myInt) { this.myInt = myInt; } 

for static property no need setter

 static int myInt; static void setMyInt(int myInt) { (your class name).myInt = myInt; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.