Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training

Sir Please Explain why inner classes cant have static declarations and whether all 4 inner classes(regular,method local,anonymous,static) have this rule.

Hi Tarun,


First, you don't have that restriction with static nested classes. For example this code works:


public class Outer {
	public static class Nested {		
		static int x = 4;
	}
}


Not only it works, it will also be useful when it comes to access the x variable. For example, if you ever want to change the value of x from outside the above code fragment, you can simply do that like this:


Outer.Nested.x = 4;



However, the following code doesn't work. Note the lack of 'static' in the inner class declaration:


public class Outer {
	public class Inner {		
		static int x = 4;
	}
}


The reason why it doesn't work is simply because there wouldn't be any static use of that variable following the contract of the non-static inner classes. In other words, inner classes are not supposed to be used without instantiating. For example, you may argue that you should be able to access x like this:


Outer.Inner.x = 4;


This however does not compile because this is a pure static access of the Inner class through Outer class without instantiating either of them. The sole purpose of the non-static inner classes is to be stick with an instance of the outer class, and hence maintain the ability to access the outer class instance variables. By letting 'x' access like this, we are just diminishing that use.


In a nutshell, this reason for this limitation is only an enforcement to stick with the intended contract of inner classes and nested classes. Other than that, there is nothing that would technically block you from having static members in a non-static inner class.


ExamLab © 2008 - 2024