java内部类访问规则

来源:互联网 发布:淘宝上的全友是真的吗 编辑:程序博客网 时间:2024/05/19 08:40
public class ClassOuter {
private static int x = 3;


/**
* 放里边,有啥好处?将ClassInner放在外面,我们如果想访问ClassOuter中的成员变量,
* 就不得不创建一个ClassOuter对象。孙悟空想访问牛摩魔王的心脏,就得先找到牛魔王,
* 再找到其心脏,牛魔王.get心脏()。当孙悟空跑到牛魔王的肚子里去了之后,就可以直 接访问牛魔王的心脏。

* 内部类的访问规则: 1、内部类可以直接访问其外部类的成员,包括私有成员。为什么呢?
* 之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,该引用 为: 外部类名.this
* 2、牛魔王想访问孙悟空就没那么方便了。外部类要访问 内部类,必须建立内部类对象 。

* 注意:1、当外部类中定义了静态成员,该内部类必须是静态的; 2、当外部类的中静态方法访问内部类时,内部类也必须是静态的
*/


/*
* 这个内部类在外部类成员的位置上,私有修饰(唯的一类可以被private修饰的情况)

* public、protected、private、static 是对成员元素(如:成员变量,成员方法,成员内部类)的
* 修饰符,而不能用在方法中的局部元素(如:方法中的局部内部类)
*/


// 成员内部类
public class ClassInner { // private class ClassInner
int x = 4;


void innerShow() {
int x = 5;
System.out.println("inner show:" + x);
System.out.println("inner show:" + this.x);
System.out.println("inner show:" + ClassInner.this.x);
System.out.println("inner show:" + ClassOuter.this.x);
}
}


static class StaticInner {
// 方法是非静态的,所以要通过对象来调用
void InnerShow() {
// Cannot make a static reference to the non-static field
// x,因为静态没有this对象
System.out.println("static inner show " + x);
}


static void staticInnerShow() {
System.out.println("static inner static show " + x);
}
}


public void show() {
ClassInner inner = new ClassInner();
inner.innerShow();


new StaticInner().InnerShow();
}


public void display(final int z) {
//局部内部类只能访问被final修饰的局部变量,这是一个规则,可为什么呢?
final int y = 4;
// 局部内部类 不能被static,private等修饰成员的关键字修饰,所以局部内部类里面不能有静态方法
class Inner {
/**
* 如果它是静态的方法,那内部类就要是static,而局部内部类不成被修饰成员的修饰符修饰
* */
void show() {
System.out.println("inner class in display  " + x);
/*
* Cannot refer to a non-final variable y inside an inner class 
* defined in a different method
*/
System.out.println("inner class in display  " + y);
System.out.println("inner class in display  " + z);
}
}
//要在类的后面创建对象
new Inner().show();
}

//匿名内部类

}


class ClassTest {
public static void main(String[] args) {
ClassOuter outer = new ClassOuter();
outer.show();
System.out.println("---------------------");
// 直接访问内部类中的成员? ---------外部名.内部名
ClassOuter.ClassInner inner = new ClassOuter().new ClassInner();
// 直接访问静态内部类的中的成员
new ClassOuter.StaticInner().InnerShow();
ClassOuter.StaticInner.staticInnerShow();

new ClassOuter().display(7);
}
}


/**
 * 当描述事件时,事物的内部还有事物,该事物用内部类来描述。因为内部事物在使用外部事物的内容。
 * */
原创粉丝点击