Is there any way to create a method in Java that can be accessed from other classes without making the method static? As all the solutions I have seen online say to make the method static don't work for me as I am trying to reference a non-static variable from within the method. The variable I am referenceing is this
(referring to the class it is in).
Asked
Active
Viewed 44 times
-1

Crafty
- 11
- 5
-
Why do you need `this` for a global method? What are you trying to do with it? – Sweeper Apr 17 '22 at 15:30
-
2If you need to reference `this`, it's not a global method, as it's bound to a single instance. If other code is to use that method, they'll need to create an instance (or perhaps use a shared instance). – Rob Spoor Apr 17 '22 at 15:32
-
How do you expect the other classes to get their value of `this` for your class? – Louis Wasserman Apr 17 '22 at 15:52
-
Also consider using an `enum` to enforce the singleton property, suggested [here](https://stackoverflow.com/q/4709175/230513) – trashgod Apr 17 '22 at 16:06
1 Answers
0
As mentioned in the comments, if you need to reference this
, it's not a global method, as it's bound to a single instance. If other code is to use that method, they'll need to create an instance.

rikyeah
- 1,896
- 4
- 11
- 21