I have the following two classes:
public class A{
private String s;
public A(String s){
this.s = s;
}
}
public class B{
private static final String STR = "String";
public void doAction(){
A a = new A(STR); //Does it look really wierd?
}
}
I've never passed the static final field as a constructor parameter, so can it lead to potential bugs? Should we avoid it or we can do that if it seems concise.
I've never passed the static final field as a constructor parameter, so can it lead to potential bugs?
This cannot lead to a bug, because doAction is an instance method. All static fields with initializers will be initialized before the first instance method is called, so you are safe.
Should we avoid it or we can do that if it seems concise?
Using a static final field, which is effectively a String constant, inside an instance method, is а perfectly valid choice.
You shouldn't worry if the field is immutable (like in your case: String is immutable data structure). With mutable objects (for example arrays) you should consider that all changes to this field in one object will be visible to other objects with the same field whether it is static or not. These code doesn't look weird.
String is a reference type, but it works like a primitive type sometimes. If you use a String object as an argument, it will be copied, like other primitive variables. I don't understand the reason you pass a class variable as an argument of other object. But it will not occur any problem caused by sharing of an attribute between objects of this class.
Related
How to create immutable objects in Java?
Which objects should be called immutable?
If I have class with all static members is it immutable?
Below are the hard requirements of an immutable object.
Make the class final
make all members final, set them
explicitly, in a static block, or in the constructor
Make all members private
No Methods that modify state
Be extremely careful to limit access to mutable members(remember the field may be final but the object can still be mutable. ie private final Date imStillMutable). You should make defensive copies in these cases.
The reasoning behind making the class final is very subtle and often overlooked. If its not final people can freely extend your class, override public or protected behavior, add mutable properties, then supply their subclass as a substitute. By declaring the class final you can ensure this won't happen.
To see the problem in action consider the example below:
public class MyApp{
/**
* #param args
*/
public static void main(String[] args){
System.out.println("Hello World!");
OhNoMutable mutable = new OhNoMutable(1, 2);
ImSoImmutable immutable = mutable;
/*
* Ahhhh Prints out 3 just like I always wanted
* and I can rely on this super immutable class
* never changing. So its thread safe and perfect
*/
System.out.println(immutable.add());
/* Some sneak programmer changes a mutable field on the subclass */
mutable.field3=4;
/*
* Ahhh let me just print my immutable
* reference again because I can trust it
* so much.
*
*/
System.out.println(immutable.add());
/* Why is this buggy piece of crap printing 7 and not 3
It couldn't have changed its IMMUTABLE!!!!
*/
}
}
/* This class adheres to all the principles of
* good immutable classes. All the members are private final
* the add() method doesn't modify any state. This class is
* just a thing of beauty. Its only missing one thing
* I didn't declare the class final. Let the chaos ensue
*/
public class ImSoImmutable{
private final int field1;
private final int field2;
public ImSoImmutable(int field1, int field2){
this.field1 = field1;
this.field2 = field2;
}
public int add(){
return field1+field2;
}
}
/*
This class is the problem. The problem is the
overridden method add(). Because it uses a mutable
member it means that I can't guarantee that all instances
of ImSoImmutable are actually immutable.
*/
public class OhNoMutable extends ImSoImmutable{
public int field3 = 0;
public OhNoMutable(int field1, int field2){
super(field1, field2);
}
public int add(){
return super.add()+field3;
}
}
In practice it is very common to encounter the above problem in Dependency Injection environments. You are not explicitly instantiating things and the super class reference you are given may actually be a subclass.
The take away is that to make hard guarantees about immutability you have to mark the class as final. This is covered in depth in Joshua Bloch's Effective Java and referenced explicitly in the specification for the Java memory model.
Just don't add public mutator (setter) methods to the class.
Classes are not immutable, objects are.
Immutable means: my public visible state cannot change after initialization.
Fields do not have to be declared final, though it can help tremendously to ensure thread safety
If you class has only static members, then objects of this class are immutable, because you cannot change the state of that object ( you probably cannot create it either :) )
To make a class immutable in Java , you can keep note of the following points :
1. Do not provide setter methods to modify values of any of the instance variables of the class.
2. Declare the class as 'final' . This would prevent any other class from extending it and hence from overriding any method from it which could modify instance variable values.
3. Declare the instance variables as private and final.
4. You can also declare the constructor of the class as private and add a factory method to create an instance of the class when required.
These points should help!!
From oracle site, how to create immutable objects in Java.
Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
Make all fields final and private.
Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
If the instance fields include references to mutable objects, don't allow those objects to be changed:
I. Don't provide methods that modify the mutable objects.
II. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
An immutable object is an object that will not change its internal state after creation. They are very useful in multithreaded applications because they can be shared between threads without synchronization.
To create an immutable object you need to follow some simple rules:
1. Don't add any setter method
If you are building an immutable object its internal state will never change. Task of a setter method is to change the internal value of a field, so you can't add it.
2. Declare all fields final and private
A private field is not visible from outside the class so no manual changes can't be applied to it.
Declaring a field final will guarantee that if it references a primitive value the value will never change if it references an object the reference can't be changed. This is not enough to ensure that an object with only private final fields is not mutable.
3. If a field is a mutable object create defensive copies of it for
getter methods
We have seen before that defining a field final and private is not enough because it is possible to change its internal state. To solve this problem we need to create a defensive copy of that field and return that field every time it is requested.
4. If a mutable object passed to the constructor must be assigned to a
field create a defensive copy of it
The same problem happens if you hold a reference passed to the constructor because it is possible to change it. So holding a reference to an object passed to the constructor can create mutable objects. To solve this problem it is necessary to create a defensive copy of the parameter if they are mutable objects.
Note that if a field is a reference to an immutable object is not necessary to create defensive copies of it in the constructor and in the getter methods it is enough to define the field as final and private.
5. Don't allow subclasses to override methods
If a subclass override a method it can return the original value of a mutable field instead of a defensive copy of it.
To solve this problem it is possible to do one of the following:
Declare the immutable class as final so it can't be extended
Declare all methods of the immutable class final so they can't be overriden
Create a private constructor and a factory to create instances of the immutable class because a class with private constructors can't be extended
If you follow those simple rules you can freely share your immutable objects between threads because they are thread safe!
Below are few notable points:
Immutable objects do indeed make life simpler in many cases. They are especially applicable for value types, where objects don't have an identity so they can be easily replaced and they can make concurrent programming way safer and cleaner (most of the notoriously hard to find concurrency bugs are ultimately caused by mutable state shared between threads).
However, for large and/or complex objects, creating a new copy of the object for every single change can be very costly and/or tedious. And for objects with a distinct identity, changing an existing objects is much more simple and intuitive than creating a new, modified copy of it.
There are some things you simply can't do with immutable objects, like have bidirectional relationships. Once you set an association value on one object, it's identity changes. So, you set the new value on the other object and it changes as well. The problem is the first object's reference is no longer valid, because a new instance has been created to represent the object with the reference. Continuing this would just result in infinite regressions.
To implement a binary search tree, you have to return a new tree every time: Your new tree will have had to make a copy of each node that has been modified (the un-modified branches are shared). For your insert function this isn't too bad, but for me, things got fairly inefficient quickly when I started to work on delete and re-balance.
Hibernate and JPA essentially dictate that your system uses mutable objects, because the whole premise of them is that they detect and save changes to your data objects.
Depending on the language a compiler can make a bunch of optimizations when dealing with immutable data because it knows the data will never change. All sorts of stuff is skipped over, which gives you tremendous performance benefits.
If you look at other known JVM languages (Scala, Clojure), mutable objects are seen rarely in the code and that's why people start using them in scenarios where single threading is not enough.
There's no right or wrong, it just depends what you prefer. It just depends on your preference, and on what you want to achieve (and being able to easily use both approaches without alienating die-hard fans of one side or another is a holy grail some languages are seeking after).
Don't provide "setter" methods — methods that modify fields or
objects referred to by fields.
Make all fields final and private.
Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
If the instance fields include references to mutable objects, don't allow those objects to be changed:
Don't provide methods that modify the mutable objects.
Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
First of all, you know why you need to create immutable object, and what are the advantages of immutable object.
Advantages of an Immutable object
Concurrency and multithreading
It automatically Thread-safe so synchronization issue....etc
Don't need to copy constructor
Don't need to implementation of clone.
Class cannot be override
Make the field as a private and final
Force callers to construct an object completely in a single step, instead of using a no-Argument constructor
Immutable objects are simply objects whose state means object's data can't change after the
immutable object are constructed.
please see the below code.
public final class ImmutableReminder{
private final Date remindingDate;
public ImmutableReminder (Date remindingDate) {
if(remindingDate.getTime() < System.currentTimeMillis()){
throw new IllegalArgumentException("Can not set reminder" +
" for past time: " + remindingDate);
}
this.remindingDate = new Date(remindingDate.getTime());
}
public Date getRemindingDate() {
return (Date) remindingDate.clone();
}
}
Minimize mutability
An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object.
JDK immutable classes: String, the boxed primitive classes(wrapper classes), BigInteger and BigDecimal etc.
How to make a class immutable?
Don’t provide any methods that modify the object’s state (known as mutators).
Ensure that the class can’t be extended.
Make all fields final.
Make all fields private.
This prevents clients from obtaining access to mutable objects referred to by fields and modifying these objects directly.
Make defensive copies.
Ensure exclusive access to any mutable components.
public List getList() {
return Collections.unmodifiableList(list); <=== defensive copy of the mutable
field before returning it to caller
}
If your class has any fields that refer to mutable objects, ensure that clients of the class cannot obtain references to these objects. Never initialize such a field to a client-provided object reference or return the object reference from an accessor.
import java.util.Date;
public final class ImmutableClass {
public ImmutableClass(int id, String name, Date doj) {
this.id = id;
this.name = name;
this.doj = doj;
}
private final int id;
private final String name;
private final Date doj;
public int getId() {
return id;
}
public String getName() {
return name;
}
/**
* Date class is mutable so we need a little care here.
* We should not return the reference of original instance variable.
* Instead a new Date object, with content copied to it, should be returned.
* */
public Date getDoj() {
return new Date(doj.getTime()); // For mutable fields
}
}
import java.util.Date;
public class TestImmutable {
public static void main(String[] args) {
String name = "raj";
int id = 1;
Date doj = new Date();
ImmutableClass class1 = new ImmutableClass(id, name, doj);
ImmutableClass class2 = new ImmutableClass(id, name, doj);
// every time will get a new reference for same object. Modification in reference will not affect the immutability because it is temporary reference.
Date date = class1.getDoj();
date.setTime(date.getTime()+122435);
System.out.println(class1.getDoj()==class2.getDoj());
}
}
For more information, see my blog:
http://javaexplorer03.blogspot.in/2015/07/minimize-mutability.html
an object is called immutable if its state can not be changed once created. One of the most simple way of creating immutable class in Java is by setting all of it’s fields are final.If you need to write immutable class which includes mutable classes like "java.util.Date". In order to preserve immutability in such cases, its advised to return copy of original object,
Immutable Objects are those objects whose state can not be changed once they are created, for example the String class is an immutable class. Immutable objects can not be modified so they are also thread safe in concurrent execution.
Features of immutable classes:
simple to construct
automatically thread safe
good candidate for Map keys and Set as their internal state would not change while processing
don't need implementation of clone as they always represent same state
Keys to write immutable class:
make sure class can not be overridden
make all member variable private & final
do not give their setter methods
object reference should not be leaked during construction phase
The following few steps must be considered, when you want any class as an immutable class.
Class should be marked as final
All fields must be private and final
Replace setters with constructor(for assigning a value to a
variable).
Lets have a glance what we have typed above:
//ImmutableClass
package younus.attari;
public final class ImmutableExample {
private final String name;
private final String address;
public ImmutableExample(String name,String address){
this.name=name;
this.address=address;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
}
//MainClass from where an ImmutableClass will be called
package younus.attari;
public class MainClass {
public static void main(String[] args) {
ImmutableExample example=new ImmutableExample("Muhammed", "Hyderabad");
System.out.println(example.getName());
}
}
Commonly ignored but important properties on immutable objects
Adding over to the answer provided by #nsfyn55, the following aspects also need to be considered for object immutability, which are of prime importance
Consider the following classes:
public final class ImmutableClass {
private final MutableClass mc;
public ImmutableClass(MutableClass mc) {
this.mc = mc;
}
public MutableClass getMutClass() {
return this.mc;
}
}
public class MutableClass {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
public class MutabilityCheck {
public static void main(String[] args) {
MutableClass mc = new MutableClass();
mc.setName("Foo");
ImmutableClass iMC = new ImmutableClass(mc);
System.out.println(iMC.getMutClass().getName());
mc.setName("Bar");
System.out.println(iMC.getMutClass().getName());
}
}
Following will be the output from MutabilityCheck :
Foo
Bar
It is important to note that,
Constructing mutable objects on an immutable object ( through the constructor ), either by 'copying' or 'cloing' to instance variables of the immutable described by the following changes:
public final class ImmutableClass {
private final MutableClass mc;
public ImmutableClass(MutableClass mc) {
this.mc = new MutableClass(mc);
}
public MutableClass getMutClass() {
return this.mc;
}
}
public class MutableClass {
private String name;
public MutableClass() {
}
//copy constructor
public MutableClass(MutableClass mc) {
this.name = mc.getName();
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
still does not ensure complete immutability since the following is still valid from the class MutabilityCheck:
iMC.getMutClass().setName("Blaa");
However, running MutabilityCheck with the changes made in 1. will result in the output being:
Foo
Foo
In order to achieve complete immutability on an object, all its dependent objects must also be immutable
From JDK 14+ which has JEP 359, we can use "records". It is the simplest and hustle free way of creating Immutable class.
A record class is a shallowly immutable, transparent carrier for a fixed set of fields known as the record components that provides a state description for the record. Each component gives rise to a final field that holds the provided value and an accessor method to retrieve the value. The field name and the accessor name match the name of the component.
Let consider the example of creating an immutable rectangle
record Rectangle(double length, double width) {}
No need to declare any constructor, no need to implement equals & hashCode methods. Just any Records need a name and a state description.
var rectangle = new Rectangle(7.1, 8.9);
System.out.print(rectangle.length()); // prints 7.1
If you want to validate the value during object creation, we have to explicitly declare the constructor.
public Rectangle {
if (length <= 0.0) {
throw new IllegalArgumentException();
}
}
The record's body may declare static methods, static fields, static initializers, constructors, instance methods, and nested types.
Instance Methods
record Rectangle(double length, double width) {
public double area() {
return this.length * this.width;
}
}
static fields, methods
Since state should be part of the components we cannot add instance fields to records. But, we can add static fields and methods:
record Rectangle(double length, double width) {
static double aStaticField;
static void aStaticMethod() {
System.out.println("Hello Static");
}
}
public class SomeClass {
private static final SomeClass INSTANCE = new SomeClass();
private SomeClass() {}
public static SomeClass getInstance() {return INSTANCE;}
public static void main(String[] args) {
System.out.println(getInstance());
}
}
Why does the getInstance method always return the same reference every time?
The reason is that the field INSTANCE is both static and final.
static means its scope is bound to the enclosing class, and not any single instance of that class. (Even though you're not creating any instances of it anyway.) In a running Java program, there's only one of each class, even though a class may have many instances.
final means that the value of this field cannot be changed after it's initialised.
Because it's static, there's only one "slot" for the object, and because it's final the contents of this slot will never change, which is why returning those contents will always return the same thing.
You're assigning a reference to a constant (INSTANCE), and your getInstance method returns that constant, so yes, it always returns the same reference.
The reason is because you have declared the instance
private static final SomeClass INSTANCE = new SomeClass();
as final and static , so the instance will be allocated a single memory and that also be constant, therefore it is using singleton pattern
Take a look at this stuff -
Implementation of Singleton Pattern Class in Java Introduction
Yes it will return the same reference always as long as the class is loaded. Its static final
INSTANTA is declared final, which means its value cannot be changed once it has been initialized. Hence, program guarantees that getInstanta returns same instance always.
You declared both method and constant static. This means it is a member of the class instead of an object created from that class. As the class only exists once it will always return the same object. Furthermore since your variable is final it can never be assigned to a new object.
what i basicly want is this:
public class Test
{
private static final Integer a;
public Test(Integer a)
{
this.a = a;
}
}
This obviously doesn't work, cause the 2nd created instance would try to override the final variable.
So is there a way to give all the instances the same immutable value via the constructor?
Static final values should be initialized in a static context, not by instances.
One options is to set the value in the declaration:
private static final Integer a=FileConfig.getInstance().getA();
Each class can have a static {} block where code is called to initialize the static parts of the class.
static {
a = FileConfig.getInstance().getA();
}
Finally, you can set the value from a static method
private static int getA() {
return FileConfig.getInstance().getA();
}
private static final Integer a=getA();
In closure, static instance initialization does not belong in instance constructors.
If the configuration values change sometimes, there is simply no reason to store the value a in a static final variable. If you want to create each instance with the constant a in the constructor, what is the purpose of a static field in the first place? Somehow, when you call the constructor for the first time, you are passing in a value from somewhere. If the value deserves to be static and final, you can acquire it from within the static initializer. If the configuration is not a singleton, but every instance always produces the same value of a, you could easily do a = new FileConfig().getA();.
Other than that, you could make the value non-final, and rest assured that since you always put in the same value of a, the static variable will not change.
Still, you could make a a final instance variable of the class, set in the constructor.
So is there a way to give all the instances the same immutable value via the constructor?
I assume you want a value to be assigned to a the first time an object of type Test is created but not when any subsequent instance is created. In that case you cannot declare it final. a will be null initially, the constructor has to check if it is null and assign it a value in that case.
But I urge you to look at the design, especially why the caller have to provide the value. Isn't it counter-intuitive that after the second Test object is created Test.a does not change in the following case?
// assume this is the first `Test` object created:
Test t = new Test(5); // Test.a is 5
Test t = new Test(6); // Test.a is *still* 5
I have several final properties defined in a Java class with constructor which has all the information to initialize the properties.
public final class A {
private final Object prop1;
private final Object prop2;
public A(Object someObj, String prop1Str, String prop2Str) {
//initialize prop1 and prop2 based on information provided from someObj, prop1Str and prop2Str parameter (1)
}
}
I would like to introduce a new constructor in class A with following signature and semantic
public A(Object obj1, Object obj2, String prop1Str, String prop2Str) {
//use obj1 and obj2 to initialize the someObj
//initialize prop1 and prop2 based on information provided from someObj, prop1Str and prop2Str parameter (1)
}
How can I reuse the code in (1)? I tried with helper private methods but Java6 gives me a compilation error since the properties of the class are final and they may not have been initialized.
EDIT:
Note that I can not call the first constructor from the second one in the first line since first I need to do some calculations and then reuse the code in question.
You've found a shortcoming of final :-)
Java must make sure that all final fields are initialized when the constructor is finished. Because of various other limitations, that means the fields must be assigned inside the code block of the constructor.
Workarounds:
Use static helper methods (which, by design, don't depend on the state of the class and therefore any final fields).
Use a builder pattern (put all parameters in a helper class which has a build() method that returns the desired result).
Don't use final. You can get the same event by omitting setters. If you are afraid that code in the class might change the fields, move them to a new base class.
Firstly, are you sure your constructors are not getting out of hand?
If you are determined (for now) on going for many constructor root, then you can call one constructor from another. Needs to be first line of constructor usig this(); syntax, which replaces implicit or explicit super();.
public A(Object obj, String prop1Str, String prop2Str) {
this(obj, obj, prop1Str, prop2Str);
}
public A(Object obj1, Object obj2, String prop1Str, String prop2Str) {
// ...
}
You can, of course, transform arguments by using more complicated expressions instead of just the plain passed-in argument. For instance:
public A(Object obj, Object prop1Obj, String prop2Str) {
this(obj, maskNull(obj), String.valueOf(prop1Str), prop2Str);
}
Constructors are there to initialise an object into a valid state. For more complex processing, you might want to add a static creation method. The method might even have a meaning name to indicate what it is doing.
you should call this(obj1, prop1Str, prop2Str). This must be the first executable line in the second constructor.
Building a multi-language application in Java. Getting an error when inserting String value from R.string resource XML file:
public static final String TTT = (String) getText(R.string.TTT);
This is the error message:
Error: Cannot make a static reference to the non-static method getText(int) from the type
Context
How is this caused and how can I solve it?
Since getText() is non-static you cannot call it from a static method.
To understand why, you have to understand the difference between the two.
Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:
SomeClass myObject = new SomeClass();
To call an instance method, you call it on the instance (myObject):
myObject.getText(...)
However a static method/field can be called only on the type directly, say like this:
The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.
... = SomeClass.final
And the two cannot work together as they operate on different data spaces (instance data and class data)
Let me try and explain. Consider this class (psuedocode):
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = "0";
}
Now I have the following use case:
Test item1 = new Test();
item1.somedata = "200";
Test item2 = new Test();
Test.TTT = "1";
What are the values?
Well
in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99
In other words, TTT is a datum that is shared by all the instances of the type. So it make no sense to say
class Test {
string somedata = "99";
string getText() { return somedata; }
static string TTT = getText(); // error there is is no somedata at this point
}
So the question is why is TTT static or why is getText() not static?
Remove the static and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText() that require it to be non-static?
There are some good answers already with explanations of why the mixture of the non-static Context method getText() can't be used with your static final String.
A good question to ask is: why do you want to do this? You are attempting to load a String from your strings resource, and populate its value into a public static field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context into your other classes and call context.getText(R.string.TTT) from within them.
public class NonActivity {
public static void doStuff(Context context) {
String TTT = context.getText(R.string.TTT);
...
}
}
And to call this from your Activity:
NonActivity.doStuff(this);
This will allow you to access your String resource without needing to use a public static field.
for others that find this in the search:
I often get this one when I accidentally call a function using the class name rather than the object name. This typically happens because i give them too similar names : P
ie:
MyClass myclass = new MyClass();
// then later
MyClass.someFunction();
This is obviously a static method. (good for somethings)
But what i really wanted to do (in most cases was)
myclass.someFunction();
It's such a silly mistake, but every couple of months, i waste about 30 mins messing with vars in the "MyClass" definitions to work out what im doing wrong when really, its just a typo.
Funny note: stack overflow highlights the syntax to make the mistake really obvious here.
You can either make your variable non static
public final String TTT = (String) getText(R.string.TTT);
or make the "getText" method static (if at all possible)
getText is a member of the your Activity so it must be called when "this" exists. Your static variable is initialized when your class is loaded before your Activity is created.
Since you want the variable to be initialized from a Resource string then it cannot be static. If you want it to be static you can initialize it with the String value.
You can not make reference to static variable from non-static method.
To understand this , you need to understand the difference between static and non-static.
Static variables are class variables , they belong to class with their only one instance , created at the first only.
Non-static variables are initialized every time you create an object of the class.
Now coming to your question, when you use new() operator we will create copy of every non-static filed for every object, but it is not the case for static fields. That's why it gives compile time error if you are referencing a static variable from non-static method.
This question is not new and existing answers give some good theoretical background. I just want to add a more pragmatic answer.
getText is a method of the Context abstract class and in order to call it, one needs an instance of its subclass (Activity, Service, Application or other). The problem is, that the public static final variables are initialized before any instance of Context is created.
There are several ways to solve this:
Make the variable a member variable (field) of the Activity or other subclass of Context by removing the static modifier and placing it within the class body;
Keep it static and delay the initialization to a later point (e.g. in the onCreate method);
Make it a local variable in the place of actual usage.
Yes u can make call on non-static method into static method because we need to remember first' we can create an object that's class we can call easyly on non -static method into static mathod