java - Are values returned by static method are static? -
please consider code
public class utilities { public static myclass getmyclass() { myclass cls = new myclass(); return cls; } }
will static method return new instance of myclass
every time called? or going return reference same instance on , over?
declaring method static
means class method , can called on class without instance (and can't access instance members because there's no object in context use - no this
).
look @ code below. expected output:
[1] different [2] same
if want variable have lifetime of class , return same object every time declare variable static
in class:
public static string getthing(){ string r=new string("abc");//created every time method invoked. return r; } private static string sr=new string("abc");//static member - 1 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"); } }
Comments
Post a Comment