Topic: 关于内部类

  Print this page

1.关于内部类 Copy to clipboard
Posted by: floweret
Posted on: 2002-12-02 22:45

假设有个top-level class 叫OuterClass,OuterClass中有个member class叫InnerClass,如果我要创建InnerClass的实例就必须用如下语句:
InnerClass objInnerClass=new OuterClass().new InnerClass();

假设还有个top-level class也叫InnerClass,并且和OuterClass在同一个目录夹下,设置为同一个package中的类,因为编译OuterClass产生两个class文件是OuterClass.java和OuterClass$InnerClass.java,编译top-leve InnerClass将产生InnerClass.java

现在我要在OuterClass中创建top-level InnerClass的实例,如果按一般的写法 InnerClass objI=new InnerClass();编译时就产生如下信息:
non-static variable this cannot be referenced from a static context

如果这两个类名相同的话,我如何能创建top-level InnerClass的实例呢?

2.How about this [Re: floweret] Copy to clipboard
Posted by: snowbug
Posted on: 2002-12-02 23:06

Did you try this:
package1.InnerClass obj1 = new package1.InnerClass();

3.Re:关于内部类 [Re: floweret] Copy to clipboard
Posted by: floweret
Posted on: 2002-12-02 23:30

还是不行

是不是Java对此有限制,同一个包中top-level class 和 inner class不能同名呢

4.I c [Re: floweret] Copy to clipboard
Posted by: snowbug
Posted on: 2002-12-03 10:21

Oh, I see, the problem you have is not because of creating the class, It has something to do with the static and non-static references.
I just did a quick try and it worked with no problem. Could you please post you code here (just the relavent part)?

5.Re:关于内部类 [Re: floweret] Copy to clipboard
Posted by: floweret
Posted on: 2002-12-03 10:49

我就是在看内部类时,自己突发奇想,如果创建一个非static的member class,并且和同一个包中的top-level class同名,jvm如何区分我到底要创建哪个类的实例,并无实际的代码TongueTongueTongue

OuterClass.java

class OuterClass{
class InnerClass{}
public static void main(){
new InnerClass=new OuterClass.new InnerClass();
//这里如何创建一个top-level的InnerClass的实例呢
}
}

InnerClass.java

class InnerClass{}


这两个文件是放在同一文件夹下的

6.Re:关于内部类 [Re: floweret] Copy to clipboard
Posted by: snowbug
Posted on: 2002-12-03 12:14

Top Level Class Bar:

package pkg;
public class Bar {
public static void print(){
System.out.println("Top Class Bar");
}
}

Inner Class Bar:

package pkg;
public class Foo {

static class Bar{
public void print(){
System.out.println("Foo.Bar");
}
}

/*
//non-static version
class Bar{
public void print(){
System.out.println("Foo.Bar (non-static)");
}
}
*/

public static void main(String[] args) {
new Bar().print(); //calls the inner class Bar
//new Foo.new Bar().print(); //calls the inner class Bar, non-static version
new pkg.Bar().print(); //calls the top level class Bar
}
}


   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