内部类的学习

来源:互联网 发布:单片机上电复位电路 编辑:程序博客网 时间:2024/06/07 00:00
/*
 * 内部类的学习
 * 1.内部类可以访问外部类的成员,包括私有
 * 内部类可以访问外部类的成员,是因为内部类持有一个外部类的引用  外部类.this.
 * 2.外部类要访问内部类,必须创建内部类对象
访问格式:
1.当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中,可以直接简历内部类对象。
格式
外部类名.内部类名  变量名=外部类对象.内部类对象;
out.inner in =new out().new inner();

2.当内部类在成员位置上,就可以被成员修饰符所修饰;
比如, private :将内部类在外部类中进行封装。
static :内部类就具备static特性
  当内部类被static修饰后,就只能直接访问外部类中的static成员,出现了访问局限
  在外部其他类中,如何直接访问static 内部类的非静态成员呢?
  new  out.inner().function();
  在外部其他类中,如何直接访问static内部类的静态成员呢?
  out.inner.function();
 
  注意: 当内部类中定义了静态成员,该内部类就必须是static的。
  当外部类中的静态方法访问内部类时,内部类也必须是static的。
 
 
  当描述事物时,事物的内部还有事物,该事物适合用内部类来描述。
  因为内部事物在使用外部事物的内容
 */




class out {
static private int x=3;
void method1(){
System.out.println("out------>"+x);
}

class inner{
int x=4;
void method2(){
System.out.println("inner------>"+out.this.x);
}
}

void function(){
inner in=new inner();
in.method2();

}
}




public class Test1{
public static  void main(String [] args){
out o=new out();
o.method1();
o.function();
out.inner in=new out().new inner();
System.out.println(in.x);


}


}



0 0
原创粉丝点击