开发者

how to call method of Owner?

I have Class1开发者_StackOverflow, which has methods:

  1. setSomething()
  2. createObjectOfClass2()

Now, when I create object of Class2, is it possible to call setSomething method from it?


If you like, but you're introducing coupling, which will make separating functionality quite difficult later. Just make setSomething public and pass a reference to the first object to the second's constructor.

public class Class1 {
    Class2 object2 = null;

    public void setSomething(Object something) { ... }

    public void createObjectOfClass2() {
        object2 = new Class2(this);
    }
}

public class Class2 {
    public Class2(Class1 parent) {
        parent.setSomething(new Foo());
    }
}


Call Parent.this.method()

e.g.:

public class K1
{
public class K2
    {
    public void hello()
        {
        K1.this.setSomething();
        }

    } 

public void setSomething()
   {
   System.out.println("Set Something");
   }

public K2 createObjectOfClass2()
   {
   return new K2();
   }

public static void main(String args[])
   {
   new K1().createObjectOfClass2().hello();
   }


}


If Class2 doesn't extends Class1, then you can call setSomething() on any instance of Class1 if it's not a static method:

Class1 c = new Class1();
c.setSomething();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜