---------------------- android培训、java培训、期待与您交流! ----------------------
一、内部类(内置类,嵌套类)
内部类的访问规则:
1. 内部类可以直接访问外部累中的成员,包括私有。
之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用。格式 外部类名.this
2. 外部类要访问内部类,必须建立内部类对象。
class Outer
{
privateintx = 3;
class Inner
{
intx = 4;
void function()
{
int x = 6;
System.out.println("inner"+x);//x=6
System.out.println(this.x);//x=4
System.out.println(Outer.this.x);//x=3
}
}
void method()
{
Inner in = new Inner();
in.function();
}
}
public class InnerClass {
public static voidmain(String[] args) {
//Outer out= new Outer();
//out.method();
//直接访问内部类中的成员
Outer.Innerin = new Outer().new Inner();
in.function();
}
}
访问格式:
1(1)当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中,可以直接建立内部类对象。
格式 外部类名.内部类名 变量名 = 外部类对象.内部类对象
Outer.Inner in = new Outer().new Inner();
(2)当内部类在成员位置上,就可以被成员修饰符所修饰。
比如 private:将内部类在外部类中进行封装。
static :内部类就具备static的特性。
当内部类被static修饰后,只能直接访问外部类中的static成员。
在外部类其他类中,直接访问static内部类的非静态成员: new Outer.Inner().function();
在外部类其他类中,直接访问static内部类的静态成员: Outer.Inner.function();
注意:当内部类中定义了静态成员,该内部类必须是static的。当 外部类的静态成员访问内部类时,内部类也必须是static的。
2,内部类定义在局部时 (在方法中定义内部类)
(1)不可以被成员修饰符修饰。
(2) 可以直接访问外部类中的成员,因为还持有外部类中的引用。
当是不可以访问它所在的局部中的变量。只能访问被final修饰的局部变量。
class Outer
{
int x = 3;
void method()
{
final int y = 4;
class Inner
{
void function()
{ System.out.println(y.); }
}
new Inner().function();
}
}
public class Demo11
{
public static void main (String[] args){
new Outer().method();
}
}
二、匿名内部类
1,匿名内部类其实就是内部类的简写格式。
2,定义匿名内部类类的前提:内部类必须是继承一个类或者实现接口。
3,匿名内部类的格式:new 父类或者接口(){定义子类的内容}
4,其实匿名内部类就是一个匿名子类对象。
5,匿名内部类中定义的方法最好不要超过3个。
abstract class Absdemo
{
abstract void show();
}
class Outer
{
int x = 3;
public void function()
{
new AbsDemo()
{
void show()
{
System.out.println("x="+x);
}.show();
}
}
}
public class Demo12
{
public static void main (String[] args){
new Outer().function();
}
}
---------------------- android培训、java培训、期待与您交流! ----------------------