[SOLVED] instantiating a class from other classes of different types...
Hi,
I have created a class which, when something occurs, should call a method in the class that instantiated it. My solution for doing this so far was to send the instantiator object to the instantiated class constructor, like this:
Code:
class Test {
public Test()
{
new UsefulClass(this);
}
public void takeAction()
{
//do something
}
}
class UsefulClass
{
private Test test;
public UsefulClass(Test test)
{
this.test = test;
}
public void somethingHappened()
{
test.takeAction();
}
}
My problem is that I now also want to instantiate UsefulClass from another class, which is not of the same type. If I simply create an object from the other class in the same way, that is
Code:
new UsefulClass(this)
, then java will complain that the type does not match.
With my limited knowledge of java, I see two solutions, none of which I much like:
1. To create loops in the instantiating classes which check when a value has changed in the instantiated class, and thus take action.
2. Create separate constructors for UsefulClass, for each class that is to instantiate it.
But perhaps there is some much more elegant way to solve this?
Thank you very much!