how to call method of Owner?
I have Class1
开发者_StackOverflow, which has methods:
setSomething()
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();
精彩评论