Java 内部类以及匿名内部类

来源:互联网 发布:家庭收支知多少 编辑:程序博客网 时间:2024/04/26 19:09
内部类的访问规则:
一:定义在成员位置上
1,内部类可以直接访问外部类中的成员,包括私有.
  之所以可以直接访问外部类的成员,是因为内部类中持有一个外部类的引用,格式为:外部类名.this
2,外部类要访问内部类,必须建立内部类的对象.
class Outer{private int x =3;class Inner{int x=4;void function(){int x=5;System.out.println("inner:"+x);//the output is 5System.out.println("inner:"+this.x);//the output is 4System.out.println("inner:"+Outer.x);//the output is 3;}}void method(){Inner in =new Inner();in.function();}}
 

1,内部类的访问格式:外部类名.内部类名 变量名=外部类对象.内部类对象    Outer.Inner in=new Outer().new Inner();条件: 内部类定义在外部类的成员位置上,为非私有.

2,可以通过private修饰符将内部类在外部类中进行封装,当内部类被static修饰后,只能直接访问外部类中的static成员,出现了访问局限. 在外部其他类中,访问static修饰的内部类的未被static修饰的成员:  new Outer.Inner().function(); 在外部其他类中,直接访问static修饰的内部类的也被static修饰的成员:  Outer.Inner.function();

class Outer{private static int x=3;static class Inner{static void function(){System.out.println("inner:"+x);}}}class InnerClassDemo{public static void main(String[] args){new Outer.Inner().function();//when the function is not static Outer.Inner.function();//when the inner function is static }}
 

 * There is  one thing that must be careful : 当内部类中有static修饰的成员时,内部类必须也为被static修饰的.

 * when to use it ? 当描述事物时,如果事物的内部还有事物,就把这个事物描述为内部类,这样,内部事物可以不用创建外部类的对象同时就可以使用外部事物的内容.

二:内部类定义在局部时: 1,不可以被成员修饰符所修饰, 2,可以直接访问外部类中的成员,因为它持有外部类中的引用-Outer.this,但是不可以访问它所在的局部中的变量,非要访问时,应该将该局部变量用final修饰.

The example codes :class Outer {int x=3;void method(){final int y=4;//①class Inner{void function(){System.out.println(y);}}new Inner().function();//this sentence must be there ,can't be put at ①}}class TestOuter{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);}void show2(){System.out.println("haa");}}.show();//you can also invoke the show2 method,which is new definited,but you can only choose one of them,because 匿名对象只能调用一次某个方法.}//same as: AbsDemo d=new Inner();which is 多态AbsDemo d=new AbsDemo(){void show(){System.out.println("x="+x);}void show2(){System.out.println("haa");}};//now you can do like this :d.show();//right;d.show2();//wrong;}