Please consider this code
public class Utilities
{
public static MyClass GetMyClass()
{
MyClass cls = new MyClass();
return cls;
}
}
Will this static method return a new instance of MyClass
every time it is called? or it is going to return a reference to the same instance over and over?
Declaring a method static
means it is a class method and can be called on the class without an instance (and can't access instance members because there's no object in context to use - no this
).
Look at the code below. Expected output:
[1] Different
[2] Same
If you want a variable to have the lifetime of the class and return the same object every time also declare the variable as static
in the class:
public static String getThing(){
String r=new String("ABC");//Created every time the method is invoked.
return r;
}
private static String sr=new String("ABC");//Static member - one for the whole class.
public static String getStaticThing(){
return sr;
}
public static void main (String[] args) throws java.lang.Exception
{
String thing1=getThing();
String thing2=getThing();
if(thing1==thing2){
System.out.println("[1] Same");
}else{
System.out.println("[1] Different");
}
String thing1s=getStaticThing();
String thing2s=getStaticThing();
if(thing1s==thing2s){
System.out.println("[2] Same");
}else{
System.out.println("[2] Different");
}
}