Monday, September 12, 2011

Method Members

Every book I've read always mentioned about class members and interface members  but there isn't much written about method members (I don't know if that term fit). I did a lot of experiments and was able to come up with the golden rule on how to determine if a declaration on a method is valid:

    "Only inner classes and local variables are allowed inside a method and that the only allowed modifiers  are  final and abstract (for inner classes only )  "
So the following are all valid :
public class MemberTest {

    public void method1() {
        final int x = 1;
        int y = 2;
      
      
        abstract class InnerAbstractClass {
      
        }
      
        class Inner {
      
      
        }
      
        final class InnerFinal {
      
        }
           
    }   

}
note: an inner class is a non-static nested class


Invalid members:

public class InvalidMethodMembers {

    public void method1() {

       
        static class InnerAbstractClass {
       
        }
       

        final static class InnerStatic {
       
        }
       
        enum E { }
        interface I { } //a nested interface is explicitly static
       
       
    }
   
}

By now you might be wodering why I even bothered to come up with that statement LOL. but tell you what, said fact would really be  usefull on say your OCJP exam  where you can encounter tricky questions ,specially about the inner and nested class :) .



No comments: