views:

55

answers:

3

Hello. I have Class1, which has methods:

  1. setSomething()
  2. createObjectOfClass2()

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

A: 

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();
Roman
Class2 doesn't seem to be a subclass of Class1.
Samir Talwar
I mystificated you by bad title. Class2 is not derived from class1.
joseph
@joseph: then edit it, `method of parent` has in mind that Class2 extends Class1
Roman
yes, but how to call it on the instance that created class2?
joseph
@joseph : owner
Roman
+1  A: 

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());
    }
}
Samir Talwar
`Class2(Class1 parent)` - very strange name for the parameter where Class2 is not inherited from Class1.
Roman
Roman: "parent" was in the original title, so I went with it. I think it fits: I personally don't like using "parent" as a pseudonym for "superclass". As you said in another comment though, "owner" fits too—feel free to change it if you like.
Samir Talwar
A: 

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();
   }


}
Pierre
but I do not want create new instance, I need to call it from instance, that created the class2
joseph