Defining a class inside another class is called 'Inner Class' in Java.There are four types of inner Class: Type:
- Member Inner Class
- Partial Inner Class
- Anonymous Inner Class
- Static Inner Class
One of the most normal type of inner Class.Take Circle as an example:
class Circle {
private double radius = 0;
public static int count =1;
public Circle(double radius) {
this.radius = radius;
}
class Draw { //inner class
public void drawSahpe() {
System.out.println(radius); //private member of outer
System.out.println(count); //static member of outer
}
}
}
The member inner class can access all attributes and methods(including private and static members) of the outer class.
But when outer class and member inner class have methods or member variables with same name,hidden
will happen.We will access inner class's member by default.If we want to access the same name member of outer class,we should use:
Outer.this.member
Outer.this.method
If outer class want to access inner class's member,it should first instantiate the inner class.For example:
class Circle {
private double radius = 0;
public Circle(double radius) {
this.radius = radius;
getDrawInstance().drawSahpe(); //Instantiate before access!
}
private Draw getDrawInstance() {
return new Draw();
}
class Draw {
public void drawSahpe() {
System.out.println(radius);
}
}
}
Member Inner class depends on the outer class.If we want a inner class object we must first instantiate an outer class object:
Outter outter = new Outter();
Outter.Inner inner = outter.new Inner();
Inner class also have the access permission of private
,protected
and public
just like the other common members in outer class.
This kind of inner class is defined in a method or a scope,the access permission of this type of inner class is limited in the method or the scope.
class People{
public People() {
}
}
class Man{
public Man(){
}
public People getWoman(){
class Woman extends People{ //局部内部类
int age =0;
}
return new Woman();
}
}
Noted that Partial Inner Class can not have any modifier.
Being used the most often and making the code much easier to be maintained.
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Noted that Anonymous Inner class is the only type of inner class that doesn't have constructor.
Static Inner Class doesn't depend on the outter class,and it can't access outer class's non-static methods or member variables.
public class Test {
public static void main(String[] args) {
Outter.Inner inner = new Outter.Inner();
}
}
class Outter {
public Outter() {
}
static class Inner {
public Inner() {
}
}
}
- Each inner class can implements an interface,making multi-inheritance become possible.
- Makes it convenient to organize several classes who have logical relationships with each others,and provides good encapsulation at the same time.
- Makes it easier to code event driver.
- Makes it easier to code thread.