I have a class say ‘A’, an object ‘a’ of which creates an object ‘b’ of class’B’. Now ‘b’ runs a method which wants to create a new instance of b’s parent(please dont confuse it with inheritance) – the class which created ‘b’, which is ‘A’ as in here.
Is this anyhow possible in Java ? Or maybe some design suggestion may work.
Thanks !
Edit : As per suggestions, I am adding my design requirement too. I have an “ExitController” class, which works differently as per the caller function – like if it is invoked by a UserX, it terminates program, if it is invoked by a UserY it logs him off, etc.
Typically I should be placing an ExitController method in my User interface, but there are some constraints due to which I cant. Also, passing the parent object/classname is seeming very expensive compared to the use it offers.
Basically, you’ve to pass the parent itself or the parent type into B’s constructor. The below example illustrates the last case.
With generics you could make it more type safe. But since the functional requirement is not entirely clear, I’ve left that away.
Update as per your update, creating instances is pointless. You could just check the class type and handle accordingly. Instead of
createParent()in above example, do:This is however plain ugly. Are you really not allowed to add another method to the
Userinterface? Otherwise the following would be a better design (called the Strategy pattern):As per your last statement:
This makes no sense. Have you measured it? Show us the results.