一、定义:顾名思义,定义在另一个类内部的类。
二、原因:
1,一个内部类的对象能够访问创建它的对象的实现,包括私有数据。
2,对于同一个包中的其他类来说,内部类能够隐藏起来。
3,匿名内部类可以很方便地定义回调。
4,使用内部类对象可以非常方便的编写事件驱动程序。
三、好处:
1,隐藏你不想让别人知道的操作,即封装性。
2,一个内部类对象可以访问创建他的外部类对象的内容,甚至包括私有变量。
四、访问规则:
1,内部类可以直接访问外部类中的成员,包括私有。
之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式 外部类名.this
2,外部类要访问内部类,必须建立内部类对象。
实例:
public class InnerClassDemo {
public static void main(String[] args) {
Outer out = new Outer();
out.method();
Outer.Inner in = new Outer().new Inner();
in.function();
}
}
class Outer {
private int x = 3;
class Inner {
void function() {
System.out.println("inner:" + Outer.this.x);
Outer.this.x=4;
}
}
void method() {
Inner in = new Inner();
in.function();
}
}
public class InnerClassDemo {
public static void main(String[] args) {
Outer out = new Outer();
out.method();
Outer.Inner in = new Outer().new Inner();
in.function();
}
}
class Outer {
private int x = 3;
class Inner {
void function() {
System.out.println("inner:" + Outer.this.x);
Outer.this.x=4;
}
}
void method() {
Inner in = new Inner();
in.function();
}
}
五、访问格式:
1,当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中。
可以直接建立内部类对象。
格式
外部类名.内部类名 变量名 = 外部类对象.内部类对象;
Outer.Inner in = new Outer().new Inner();
2,当内部类在成员位置上,就可以被成员修饰符所修饰。
比如,private:将内部类在外部类中进行封装。
static:内部类就具备static的特性。
当内部类被static修饰后,只能直接访问外部类中的static成员。出现了访问局限。
在外部其他类中,如何直接访问static内部类的非静态成员呢?
new Outer.Inner().function();
在外部其他类中,如何直接访问static内部类的静态成员呢?
uter.Inner.function();
注意:当内部类中定义了静态成员,该内部类必须是static的。
当外部类中的静态方法访问内部类时,内部类也必须是static的。
实例:
public class InnerClassDemo1 {
public static void main(String[] args){
OuterLei.method();//直接访问外部类的
OuterLei.Inner1.function();//访问static内部类中的静态成员
new OuterLei.Inner1().function();//访问static内部类的非静态成员
OuterLei.Inner2 in=new OuterLei().new Inner2();//直接访问内部类中的成员。
in.show();
}
}
class OuterLei{
private static int x=3;
static class Inner1{//静态内部类
static void function(){
System.out.println("inner:"+x);
}
}
class Inner2{
void show(){
System.out.println("inner2 show");
}
}
public static void method(){
Inner1.function();
}
}
六、匿名内部类:
1,匿名内部类其实就是内部类的简写格式。
2,定义匿名内部类的前提:
内部类必须是继承一个类或者实现接口。
3,匿名内部类的格式: new 父类或者接口(){定义子类的内容}
4,其实匿名内部类就是一个匿名子类对象。而且这个对象有点胖。可以理解为带内容的对象。
5,匿名内部类中定义的方法最好不要超过3个。