黑马程序员技术交流社区
标题:
内部类定义在局部可以在其他类中被创建吗?
[打印本页]
作者:
苏伯亚
时间:
2014-4-13 10:01
标题:
内部类定义在局部可以在其他类中被创建吗?
class Outer
{
int x = 3;
void method(final int a)
{
final int y = a;
//y=a;
class Inner
{
void function()
{
System.out.println(y);
}
}
new Inner().function();
System.out.println("y="+y);
System.out.println("x="+x);
}
}
class InnerClassDemo3
{
public static void main(String[] args)
{
Outer out = new Outer();
out.method(7);
out.method(8);
Outer.Inner in=new Outer().new Inner();
in.function();
}
总是报错
Demo2.java:35: 错误: 找不到符号
Outer.Inner in=new Outer().new Inner();
^
符号: 类 Inner
位置: 类 Outer
Demo2.java:35: 错误: 找不到符号
Outer.Inner in=new Outer().new Inner();
^
符号: 类 Inner
位置: 类 Outer
2 个错误
是确实不能在其他类中创建,只能在它所在的类中被创建引用。还是我用的创建方法不对。
求交流
作者:
leon_hm
时间:
2014-4-13 10:18
package test;
public class OuterTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Outer out = new Outer();
out.method(7);
out.method(8);
// Outer.Inner in=new Outer().new Inner();
Outer.Inner2 in=new Outer().new Inner2();
in.function();
}
}
class Outer
{
int x = 3;
void method(final int a)
{
final int y = a;
//y=a;
class Inner
{
void function()
{
System.out.println(y);
}
}
new Inner().function();
System.out.println("y="+y);
System.out.println("x="+x);
}
public class Inner2
{
void function()
{
System.out.println(x);
}
}
}
复制代码
你那是定义在方法里面了。
把内部类放到方法外面就可以了。看上面的inner2
作者:
759345779
时间:
2014-4-13 10:24
内部类定义在外部类乘员位置上的时候才可以调用 Outer.Inner in=new Outer().new Inner();创建新的新的对象
定义在局部是不可以用Outer.Inner in=new Outer().new Inner();创建
可改为:
{
int x = 3;
int y = 4;
class Inner
{
void function()
{
System.out.println(y);
}
}
void method(final int a)
{
final int y = a;
new Inner().function();
System.out.println("y="+y);
System.out.println("x="+x);
}
}
复制代码
或者不用Outer.Inner in=new Outer().new Inner();创建对象就行了,不知道是不是你想要的答案
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2