×

Loading...
Ad by
  • 推荐 OXIO 加拿大高速网络,最低月费仅$40. 使用推荐码 RCR37MB 可获得一个月的免费服务
Ad by
  • 推荐 OXIO 加拿大高速网络,最低月费仅$40. 使用推荐码 RCR37MB 可获得一个月的免费服务

@

cut and paste the included code, it shows everything works fine.

package com.maple.test;

public class A {

public A()
{
System.out.println("Class A has been constructed!");
}

class C {
private int i = 0;
public C()
{
i = -1;
System.out.println("inner class C of class A has been constructed!");
}
}

public void test()
{
C c = new C();
B b = new B(this);
}

/**
* @param args
*/
public static void main(String[] args) {
A a = new A();
a.test();
System.out.println("Done test.");
}

}


package com.maple.test;

public class B {

private A a = null;
public B(A a){
this.a = a;
System.out.println("class B has been constructed!");
}

}
Report

Replies, comments and Discussions:

  • 工作学习 / 专业知识杂谈 / 有关java inner class的问题,请高手给各解答。
    I have two class A and B,define like this:
    Class A{
    ...
    class C c{
    }
    B b=new B(this);
    ...
    }
    Class B{
    B(A a){
    }
    }
    C is inner class of A,C was used by A,the error was issued from line “new B(this),it's said constructor B(A.C) is undefined,I don't want this constructor,I only need B(A a),what can I do?

    thanks!
    • try B b=new B(A.this)
    • class C c{ } 有这样的写法?发回重贴。
      • 而且我觉得他把B b=new B(this)放到了Class C的{} 里了
    • 对不起,没仔细检查,我改过了
      Class A{
      ...
      class C{
      ...
      }//end of class C
      C c=new C();
      B b=new B(this);//error occured here--
      ...
      }//end of class A
      Class B{
      B(A a){
      }
      }//end Class B
      • where did you put those 2 lines, in a method? C c=new C(); B b=new B(this);//error occured here--
        You should redesign your solution!
    • Markriver,能否给解释一下。谢了!
      • 谢谢大家,程序已改正!
        谢谢大家,程序没错,编译能通过,我搞错了,把b=new B(this)放在了A中了,实际上应该在inner class中,所以markriver的解答是对的,在inner class中要用outer class要用OutClassName.this.多谢多谢!
    • what's your intention to use inner class C here? what's the reason to cross reference class A and class B? What're the real use cases, more details please.
    • cut and paste the included code, it shows everything works fine.
      package com.maple.test;

      public class A {

      public A()
      {
      System.out.println("Class A has been constructed!");
      }

      class C {
      private int i = 0;
      public C()
      {
      i = -1;
      System.out.println("inner class C of class A has been constructed!");
      }
      }

      public void test()
      {
      C c = new C();
      B b = new B(this);
      }

      /**
      * @param args
      */
      public static void main(String[] args) {
      A a = new A();
      a.test();
      System.out.println("Done test.");
      }

      }


      package com.maple.test;

      public class B {

      private A a = null;
      public B(A a){
      this.a = a;
      System.out.println("class B has been constructed!");
      }

      }