Domanda

First day using Java. Very basic question: I have three base classes, multiply-inherited by many classes. Each of these base classes has lots of implementation with few abstract methods:

class Consumer { /* lots of stuff */ };
class Producer { /* lots of stuff */ };
class Logger { /* lots of stuff */ };

class A : public Consumer, Producer, Logger {}
...
class Z : public Consumer, Producer, Logger {}

Now I know I can turn two of three base classes into interfaces and multiple-inherit the 2 interfaces and extend one class. Inadequate because of all the implementation in these base classes that doesn't make sense to duplicate into many subclasses.

I'm reading some stuff on delegation or composition, and I don't know how to apply this here. Basically my thought processes have been patterned by my C++ experience. What is the path of least resistance to convert my C++ class structure to Java?

I can fill out the base classes more if needed, but hopefully not necessary.

È stato utile?

Soluzione 2

you have two options:

Create 3 interfaces for Consumer, Producer and Logger and make the classes A and Z implementing them. Of course for each class you have to provide an implementation. If the implementation is the same make a more generic class (it could be abstract, you probably won't need to instantiate it) implementing the 3 interfaces and then make the classes A and Z extending the abstract class.

As you said in your post it seems this solutions don't fit your needs , so use delegation instead, in the classes A and Z put 3 new fields (as instance variable) of Consumer, Producer and Logger type (you can instantiate them in the constructor) and then put methods which are wrappers for the Consumer, producer and Logger methods.

Altri suggerimenti

What is the path of least resistance to convert my C++ class structure to Java?

take a pen and paper, rethink your problem and make a design that's closer to how Java works.

There's no magical rule that will transform any given problem with multiple inheritance into another without it. Given the situation, you may want to separate concerns by creating multiple classes with a reference to each other, whereas you had only one in C++… But then it's up to the specific problem you're dealing with, how you'd build your hierarchy of classes and interfaces and how the resulting different class instances will relate to each other.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top