public class ScopeTest
{
void y()
{
final int x=11,y=22;
class B//你的这个内部类是在方法y()中的,它的作用域就在方法y()中,外面的方法和类都是无法访问的。
{
void f(){ System.out.println(x+y);}
}
}
}
class Test
{
public static void main(String[] args)
{
ScopeTest x=new ScopeTest();
ScopeTest.B k=x.new ScopeTest.B();//你这里想使用ScopeTest类中的y()方法内部的类B。这里是不能访问到的,超过了内部类B的作用域。
k.f();
}
}
class ScopeTest {
void y() {
final int x = 11, y = 22;
new B().f(x, y);
} public class B {
public void f(int x, int y) {
System.out.println(x + y);
}
}}public class TestHello {
public static void main(String[] args) {
ScopeTest x = new ScopeTest();
x.y();
System.out.println("==============");
ScopeTest.B k = x.new B();
k.f(11, 12);
}
}
ScopeTest x=new ScopeTest();
x.y();
这不就是实例化内部类了。。LZ那样的类B怎么实例化呢?
你看见了lz的代码了吧?
他把类 B 写在了方法 y() 的里面。根据Java的内部类的要求,在方法内写的类,这样的类的作用域只在该方法内部。也就是说,能实例化LZ的内部类B的唯一的地方,就是在方法y()里面。如:class ScopeTest {
void y() {
final int x = 11, y = 22;
class B {
void f() {
System.out.println(x + y);
}
}
B b = new B();//只能在y()的内部进行实例化,它的作用域在y()内部。
b.f();
}
}public class TestHello {
public static void main(String[] args) {
ScopeTest x = new ScopeTest();
x.y();
}
}
感谢一楼的解释。非常感谢。
void y() {
final int x = 11, y = 22;
class B {
void f() {
System.out.println(x + y);
}
}
B b = new B();//只能在y()的内部进行实例化,它的作用域在y()内部。
b.f();
}
public static void main(String[] args) {
ScopeTest x = new ScopeTest();
x.y();
}
}public class TestHello {
}
//output:
错误: 在类 com.wanmei.test.TestHello 中找不到主方法, 请将主方法定义为:
public static void main(String[] args)
{
int value();
}public class ScopeTest
{
MyHandle y()
{
final int x=11,y=22;
class B implements MyHandle
{
public int value(){return x+y;}
}
return new B();
}
}class Test// 执行java Test就OK
{
public static void main(String[] args)
{
ScopeTest x=new ScopeTest();
MyHandle k=x.y();
System.out.println(k.value());
}
}
但是如果把y()声明为static的话,其第一行语句就必须是final。也就是说"如果y()是static,那么类B访问y()的数据时,这些数据就必须是final”
请问是为什么?
果然还是楼主啊,我回你贴了。对了,楼主,虽说“class Test// 执行java Test就OK”没错,非公共类也可运行,但不建议这么做,这是一个编码规范的问题。