1、内部类可以直接访问外部类中的成员,包括私有。之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式为:外部类明.this
2、外部类要访问内部类,必须创建内部类对象。
1、当内部类定义在外部类的成员位置上是,而且非私有,可以在外部其他类中
可以直接建立内部类对象
格式:
外部类明.内部类名 变量名=外部类对象.内部类对象;
Outer.Inter in=new Outer().new Inner();
2、当内部类在成员位置上时,就可以成员修饰符所修饰
比如:private:将内部类在外部类中进行封装
static:内部类就具备static特性
当内部类被静态修饰后,只能访问外部类中的静态成员了,出现了访问局限。
在外部其他类中,如何直接访问静态内部类的非静态成员呢?
new Outer.Inner().function();
在外部其他类中,如何直接访问静态内部类的静态成员呢?
Outer.Inner.function();
3、注意事项:
当内部类中定义了静态成员,该内部类必须是静态的
当外部类的静态方法访问内部类时,内部类也必须是静态的
当描述事物时,事物的内部还有事物,该事物用内部类来描述
因为内部事物在使用外部类事物的内容
class Outer
{
int x=3;
private void function()
{
System.out.println("inner:"+Outer.this.x);//此时打印的是3
}
void method()
{
System.out.println(x);
}
}
class InnerClassDemo
{
public static void main(String[] args)
{
Outer.Inter in=new Outer().new Inner();
in.function();
}
}
1、不可以被成员修饰符修饰。
2、可以直接访问外部类的成员,因为还持有外部类的引用,
但是不可以访问他所在的局部中的变量,只能访问被final修饰的局部变量。
class Outer
{
int x=3;
void method(final int a)
{
class Inter //这里面就不能用private修饰了,也不能是静态的
{
final int y=4;
void function()
{
System.out.println(x);
System.out.println(y);
System.out.println(a);
}
new Inter().function();
}
}
}
class InterClassDemo3
{
public static void main(String[] args)
{
Outer out=new outer();
out.method(7);
out.method(8);//虽然是final修饰的,但这样是可以的,因为是局部变量,栈内存存放
/*
new Outer().method(7);
new Outer().method(8);
*/
}
}
1、匿名内部类其实就是内部类的简写格式
2、定义匿名内部类的前提
内部类必须是继承一个类或者是实现接口
3、匿名内部类的格式:new 父类或者接口(){定义子类的内容}
4、其实匿名内部类就是一个匿名子类对象。而且这个对象有点胖
也可以把它理解成一个带内容的对象
5、匿名内部类中定义的方法最好不要超过3个
class AbcDemo
{
abstract void show();
}
class Outer
{
int x=3;
/*
class Inter extends AbcDemo
{
void show()
{
System.out.println("method="+x);
}
}
*/
public void function()
{
//new Inter().show();//下面这个就是相当于上面这句
new AbsDemo() //***********************************整体是AbsDemo的子类对象
{
void show()
{
System.out.println("x="+x);
}
void abs()
{
System.out.println("haha");
}
}.show();//也可以调用abc()
}
}
class InterclassDemo4
{
public static void main(String[] args)
{
new Outer().function();
}
}interface Inter
{
public abstract void method();
}
/*
class Test
{
//补足代码,通过匿名内部类
static class Inner implements Inter
{
public void method()
{
System.out.println(method run);
}
}
static Inter function()
{
return new Inner();
}
}
*/
static Inter function()
{
return new Inter()
{
void method()
{
System.out.prinyln("method run");
}
};//分号不能少,这是一个return语句
}
class InterClassDemo5
{
public static void main(String[] args)
{
//Test类中有静态成员方法function()
//并且返回值肯定是一个对象,而且是Inter类型的对象
//因为只有是INter类型的对象才可以调用method方法
Test.function().method;
// Inter in=Test.function();
// in.method();
show(new Inter()
{
public void method()
{
System.out.println("method show run");
}
});
}
public static void show(Inter in)
{
in.method();
}
}内部类(嵌套类、内置类)访问规则、定义原则、静态内部类、匿名内部类
原文地址:http://blog.csdn.net/u011528448/article/details/43243121