黑马程序员技术交流社区
标题:
关于内部类常量的问题
[打印本页]
作者:
邓超军
时间:
2012-7-15 07:31
标题:
关于内部类常量的问题
class Outer
{
int x = 3;
void method(final int a)
{
final int y = 4;
class Inner
{
void function()
{
System.out.println(y);
}
}
new Inner().function();
}
}
class InnerClassDemo3
{
public static void main(String[] args)
{
Outer out = new Outer();
out.method(7);
out.method(8);//a不是常量吗?怎么还能再次被赋值?
}
}
复制代码
作者:
全海波
时间:
2012-7-15 07:43
01.class Outer
02.{
03. int x = 3;
04.
05. void method(final int a)
06. {
07. final int y = 4;
y = a;
//加一个y = a;试一下
08. class Inner
09. {
10. void function()
11. {
12. System.out.println(y);
13. }
14. }
15.
16. new Inner().function();
17.
18. }
19.}
20.
21.
22.class InnerClassDemo3
23.{
24. public static void main(String[] args)
25. {
26. Outer out = new Outer();
27. out.method(7);
28. out.method(8);//a不是常量吗?怎么还能再次被赋值?//你传的值根本就不是在同一个常量上,应该将a量赋值给y
29. }
30.
31.}
复制代码
作者:
孙飞
时间:
2012-7-15 07:44
本帖最后由 feigecal 于 2012-7-15 07:46 编辑
因为你的a是在内部 类中,内部类是一个局部内部类,a只在局部内有效,出了这个作用域会被释放,你用外部类的对象调用mehtod方法,给a赋值。调用一次赋一次,下次调用 的时候a已被释放,再说了调用的方法内没有用到a,所以不管是赋7还是8结果都是输出4。就算你方法内用到a,再次调用 时也是可以再赋值的,因为它只定义在局部内,会在调用 后被释放地
作者:
余清兰
时间:
2012-7-15 07:51
out.method(8);//a不是常量吗?怎么还能再次被赋值?
因为a虽然是个常量,但你把它作为参数定义在method方法里,
就相当于在这个方法的局部有效,a开始没有值,第一次通过out.method(7);
调用method方法把7赋给了a,等程序执行完后,方法也在内存中释放了,a之前的值也没了
第二次再通过out.method(8);调用method方法把8赋给了a,相当于是个全新的a赋了个8
这个肯定是可以赋值的
如果要测试常量是否能被第二次赋值,可以看我下面的代码,把常量y再做自增
代码运行后会提示无法为最终y指定值
class Outer
{
int x = 3;
void method(final int a)
{
final int y = 4;
class Inner
{
void function()
{
y++;
System.out.println(y+a);
}
}
new Inner().function();
}
}
class InnerClassDemo3
{
public static void main(String[] args)
{
Outer out = new Outer();
out.method(7);
out.method(8);
}
}
因为y常量一定义就有值了,y++跟y在同一个方法范围内,就无法把y再次通过自增赋值了
QQ截图20120715074114.png
(2.2 KB, 下载次数: 29)
下载附件
2012-7-15 07:41 上传
作者:
陈冲
时间:
2012-7-15 07:52
本帖最后由 陈冲 于 2012-7-15 07:55 编辑
class Outer
{
int x = 3;
void method(final int a)
{
final int y = 4;
class Inner
{
void function()
{
System.out.println(y);
}
}
new Inner().function();
}
}
class InnerClassDemo3
{
public static void main(String[] args)
{
Outer out = new Outer();
out.method(7);
out.method(8);//a不是常量吗?怎么还能再次被赋值?
}
}
复制代码
final可以修饰类,方法,变量;
final修饰的类不可以被继承;
final修饰的方法不可以被覆盖;
final修饰的变量是一个常量,只能被赋值一次;
内部类只能访问final修饰的局部变量;
当调用method(int)方法时,才对a进行初始化;且a是局部变量,生命周期在method()方法结束时就结束;
所以
out.method(7);
out.method(8);
是两次不同的调用,每次调用时,都要对a重新进行初始化;
而你在method ()方法内部没用对a进行赋值,所以不存在再次赋值的问题。
作者:
黑马-王言龙
时间:
2012-7-15 07:52
final修饰局部变量,只保证,它一但被初始化就不能再局部内再改变。
你这里的method()方法一调用结束,a就会在内存中消失。
下次再调用method(),还是可以再次初始化变量a的
作者:
周恺
时间:
2012-7-15 08:02
你的final常量定义在method方法中,当method方法执行完毕退栈以后,所有在其中声明的变量都会销毁.
无论是常量还是变量,它在哪一个大括号里面声明,它的生命周期就随着那个大括号{}结束而结束.
作者:
韩伟
时间:
2012-7-15 09:04
这个问题其实在视频中毕老师特别强调过的。首先,当系统调用out.method(7)时,method方法进栈执行,当方法执行完成之后,方法会在栈中被释放,那么变量a 就已经不存在了。当执行out.method(8)时,method方法就就再次进栈执行,同时有一个新的变量a产生。所以两次执行,变量a根本就不是一个变量,所以是没有问题的。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2