Topic: An inner class access point

  Print this page

1.An inner class access point Copy to clipboard
Posted by: arjooe
Posted on: 2002-12-28 12:41

近日,读过SCJP参考文献关于内联Clsass的章节之后,写了以下一个类以验证Classes Defined Inside Methodss对enclosing class的成员变量以及成员方法中final与非final变量的accessibility。

心得1: 在inner class中,可以读包含它的方法中的final修饰的变量,其它类型的变量一概导致编译错误,final变量等同于定义它的范围内的常量,inner class在构造时会获得一份拷贝。

心得2: 大家注意,inner class 对上一层class中的非static的变量不概不认,即使修饰final也一样。

心得3: (大多数文章并未提到的)在一个捅有inner class的成员方法中,可以对该inner class实例中的任何成员变量或成员方法(即便是private)直接引用。

以下代码在Jb8+win2k+j2sdk1.4.1_01中编译通过,希望能对各位兄弟有所帮助。代码输出如下:
Static outest variable

Static final outest variable

4

92

234

23.111113

32423

2.938402E7

234234.0

234234.0

234234.0

package te;

代码如下:

public class Example {

private float f=1.2345f;
private static String staticouterside = "Static outest variable";
private static final String staticfinalouterside = "Static final outest variable";
private final String outerside = "Outest variable";

static public void test(int aa,final int bb){
int i = aa + bb;
final int j = aa*bb;

class inner {
int a = 234;
short c = 32423;
float d = 29384019;
private double dd = 234234.;
float b = 23.111112f;

private void output(){
//System.out.printRose; cause compile error
//System.out.println(outerside); cause compile error
System.out.println(staticouterside);
System.out.println(staticfinalouterside);
System.out.println(bb);
System.out.println(j);
System.out.printlnAngel;
System.out.printlnBeer;
System.out.printlnCoffee;
System.out.printlnFood;
System.out.println(dd);
}
}

inner innertest = new inner();
innertest.output(); //invoke private method

double out = innertest.dd; //Note this statement, access private variable

System.out.println(innertest.dd); //and this
System.out.print(out); //and this
}

public static void main(String args[]) {

test(23,4);

}

}


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923