java - Why static object of non-static class cannot be created inside a method? -


i can see static object of non-static class cannot created inside method?

code:

  public class rent {        public void abc() {           system.out.println("non static method");       }       public static void def() {           system.out.println("this static method");       }   }    public class samplejava {        public static void main(string[] args) {           rent r1 = new rent();           public static rent r2; //not allowed in static method       }        public static rent r3; //allowed outside method        public void def() {           rent r4 = new rent();           public static rent r5; //not allowed in non-static method either       }   } 

there few points have consider:

  1. static data similar static method. has nothing instance. value declared static has no associated instance. exists every instance, , declared in single place in memory. if ever gets changed, change every instance of class.

  2. the access modifiers have used allowed class level , not method level. in example:

    public static void main(string[] args) {   rent r1 = new rent();   public static rent r2; //will give compile time error. }   
  3. considering purpose of "static", if declaring static object inside method scope bind particular method only.

usually static objects used maintain state.

for e.g. database connection logic may have singleton class , object of class should keep state of database connection. these objects needs , must @ class level.


Comments