内部类基本知识点

来源:互联网 发布:淘宝优惠券怎么使用 编辑:程序博客网 时间:2024/06/05 01:04

package softDay9;
/*内部类访问规则:将一个类定义在另个一类的里面,对里面那个类就称为内部类(内置类,嵌套类)
* 内部类可以直接访问外部类的成员,包括私有
* 之所以可以直接访问外部类中的成员 是因为内部类中有一个外部类的引用格式:外部名.this.XX
* 外部类如果想访问内部类,必须建立内部类对象
*
* 访问格式:
* 1.当内部类定义在外部类的成员位置上 而且非私有 可以在外部其他类中
* 可以直接建立内部类对象
* 格式:
* 外部类.内部类名 变量名 = new 外部类对象.内部类对象;
* Outer.Inner in = new Outer().new Inner();
* 2.当内部类在成员位置上,就可以被成员修饰符所修饰
* 比如:private :将内部类在外部类中进行封装
* static :内部类就具备了static的特性
* 当内部类被静态修饰后,只能直接访问外部类中的static成员 出现了局限访问
*
* 在外部其他类中 如何让<直接>访问 static内部类的非静态成员呢?
* new Outer.Inner().function();
* 在外部其他类中 如何让<直接>访问 static内部类的静态成员呢?
* Outer.Inner.function(); 但使用频率很低
*注意:
* 当内部类中定义了静态成员,该内部类必须是static的。
* 静态方法访问静态成员
* 当外部类中的静态方法访问内部类时 内部类也必须是static的
**/
public class InnerClassDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//Outer ot = new Outer();
//ot.method();

    //直接访问内部类中的成员    //Outer.Inner in = new Outer().new Inner();//直接调用内部类    //in.function();    //new Outer.Inner().function();    //Outer.Inner.function();    Outer.method();}

}
class Outer{

private static int x = 3;//私有成员变量在本类中有效   static一旦修饰则数据可以共享到内部类中 static class  Inner{    static void function(){//内部类 好处:可以不用        int x = 6;        System.out.println("inner :"+x);//X = 6; Outer.this.x = 3;    }}

// static void method(){
//
// System.out.println(x);
// Inner in = new Inner();
// in.function();
//
// }
static class Inner2{

    void show(){        Inner.function();    }}public static void method(){    new Inner2().show();}

}

0 0
原创粉丝点击