从当前实例访问实例

时间:2013-05-02 22:13:36

标签: java instance

我想获得类的实例,这个实例已经在哪里,是否可能?

注意:不嵌套类。

    class Frame {
        protected Panel p1;
        private String name;
        public Frame(String name) {
            this.name=name;
            p1=new Panel();
        }
        public String getName() {
            return name;
        }
    }

...

    class Panel {
        public Panel() {
            System.out.println("I was made in: "+Frame.this.getName()); 
                                    // but you can't do this
        }   
    }

...

    public void main(String[] args) {
        Frame f1=new Frame("first"); // should print: first
        Frame f2=new Frame("second"); // should print: second
    }

注2:我知道这种方法:

 class Frame {
        protected Panel p1;
        private String name;
        public Frame(String name) {
            this.name=name;
            p1=new Panel();
        }
        public String getName() {
            return name;
        }
    }

...

    class Panel {
                private Frame owner;
        public Panel(Frame owner) {
                        this.owner=owner; // DECLARING OWNER
            System.out.println("I was made in: "+owner.getName()); 

        }   
    }

...

    public void main(String[] args) {
        Frame f1=new Frame("first"); // should print: first
        Frame f2=new Frame("second"); // should print: second
    }

...但这并不能让我开心,如果可能的话,我想以某种方式直接访问。

3 个答案:

答案 0 :(得分:0)

给它一个机会。我不确定它是否编译,我无法检查我在哪里。但这应该是你正在寻找的一般想法。

Class A {
    B b = B.masterB;
    A() { }
    getB() { return b;}
}

Class B {
  static B masterB = new B();

    A a;
    B() {
       a=new A();
    }
    getA() { return a; }
}

class main
{

static void main(string[] args) {
  A a = new A();
  B result = a.getB();
}

答案 1 :(得分:0)

在类B中声明类型为A的实例变量。在B的构造函数中接受A类型的参数。

B的构造函数中,将this传递给A的构造函数。

class A {
    B b;
    A(B b) {
        this.b = b;
        // get the instance of B so i can call do this, for example:
        b.getA();
    }
}

class B {
    A a;
    B() {
       a=new A(this);
    }
    A getA() { return a; }

}

答案 2 :(得分:0)

您可以按以下方式覆盖方法

public class Frame {

    protected Panel p1;
    private String name;
    public Frame(String name) {
        this.name=name;
        p1=new Panel() {
            public String ownerName() {
                return getName();
            }
        };
    }
    public String getName() {
        return name;
    }


    class Panel {
        public Panel() {
            System.out.println("I was made in: "+ownerName()); 

        }

        public String ownerName() {
            return null;
        }
    }

    public static void main(String[] args) {
         Frame f1=new Frame("first"); 
         Frame f2=new Frame("second");
    }
}