
"An InnerClass is a NestedClass that is not explicitly or implicitly declared static." -- Java Language Specification, Second Edition [1]
An inner class, as used in JavaLanguage, is a class nested within another class:
class C {
class D {
}
}
Unlike a C++ nested class, an instance of a Java inner class contains an implicit, hidden reference to an instance of the outer class. You can actually obtain this reference from within the inner class, with syntax "OuterClassName.this", though this is rarely necessary:
C.this
An instance of an inner class can only live attached to an instance of the outer class. Within instance methods of the outer class, you can simply use "new D()" to create it and it will implicitly take that current outer class instance as the enclosing instance. However, if you want to create an instance of the inner class from outside the outer class, or from within a static method, you need to explicitly give the enclosing instance reference:
C c = new C();
C.D d = c.new D();
Because the inner class is considered part of the implementation of the outer class, it has access to all of the outer class's instance variables and methods.
When name conflicts arise (i.e., the inner class declares a variable with the same name as a variable in the outer class, or when using the this keyword), prefix the identifier with the name of the outer class for static variables, and prefix it with the name of the outer class plus .this. for non-static variables:
class A {
private boolean fuzzy;
class B {
private boolean fuzzy;
//These two methods act on this object's variable.
public boolean isFuzzy() {
return fuzzy;
}
public void makeFuzzy() {
fuzzy=true;
}
//These two methods act on whatever instance of A to which this
//object of type B was attached.
public boolean isAFuzzy() {
return A.this.fuzzy;
}
public void makeAFuzzy() {
A.this.fuzzy=true;
getOuter().fuzzy=true; //equivalent; see next method
}
//This method returns the object to which "A." refers, above.
public A getOuter() {
return A.this;
}
}
}
Types of Inner Class
1.Local Inner Class
2.Static Inner Classes
Yugandhar, if this helps please login to Mark As Answer. | Alert Moderator