Link to home
Start Free TrialLog in
Avatar of Tal Tene
Tal Tene

asked on

Java - How to handle very similar classes with nested classes

Hi All,

 I am having difficulties to handle the following classes gracefully:

Suppose I have the following class A:

class A{

	B b1;
	
	class B{
		
		C c1;
		D d1;
		
		class C{
		.
		.
		.
		}
		
		class D{
		.
		.
		.
		}
	
	}
}

Open in new window


and I have also class AA:

class AA{

	B b1;
	
	class B{
		
		C c1;
		E e1;
		
		class C{
		.
		.
		.
		}
		
		class E{
		.
		.
		.
		}
	
	}
}

Open in new window



I need to create and initialize objects of A or AA depending on some flag state.
Notice that class B inside class A is nesting class D whereas class B inside class AA is nesting class E !

The automatic thought I had is to derive them from some base class and use a factory.
Then I would get an object which I can use, but then I would face the need to work with D or E objects.
But I don't know exactly how to implement this idea. Is it possible at all? Is there a better way of achieving it?

Thank you!
Avatar of Surrano
Surrano
Flag of Hungary image

Hello Tal,

Sounds pretty obscure but derivation may work. However A:B and AA:B are not the same and the two C's aren't the same either.

Have the two B's implement the same interface that contains one or two initialisation functions. Is it something you are looking for?

The hardcore way is to exploit reflection but hard to tell more from this skeleton.


S.
Avatar of Tal Tene
Tal Tene

ASKER

Thank you Surrano.
I didn't exactly understand your idea. If you could add a code example I'll be grateful.
The C classes are the same (contrary to what you said), but the B's are not because one of them includes a D object and the other an E object.
I doubt that you could assign an object of type A:B:C to a variable of type AA:B:C even if they were public.

To provide code pls describe exactly how you'd create an object A and AA to understand what's common and what differs.

as.
host.javaguest.java

Notice the UserCredentials class.
It contains a reference to a different object - UserNamePassword and FirstLastNameEmail. And this is all the difference between the two classes.

Thank you tor your time, although I begin to think really about un-nesting the classes.
But then again - I cannot change the classes names because they represent JSONs. So I am not sure that would be helfull...
ASKER CERTIFIED SOLUTION
Avatar of Surrano
Surrano
Flag of Hungary image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial