tags:

views:

1063

answers:

5

Is there a way to emulate mixins or traits in java? basically, I need a way to do multiple inheritance so I can add common business logic to several classes

A: 

Java's answer to multiple inheritance is the ability to implement multiple interfaces. Of course, this means you'll get the method declarations, but not the logic.

You could try emulating mixins by composition: your Java class could define member variables that represent other classes that perform some common business logic.

In designing Java classes, I have not found the lack of C++ style multiple inheritance to inhibit the design of my architecture. You will find a way to achieve what you want to do.

David
+2  A: 

Not the way you want to do it. Effective Java recommends that you "Favor composition over inheritance". Meaning you move the common logic to other classes and delegate. This is how you get around the lack of multiple inheritance in java.

sblundy
+3  A: 

I would encapsulate all of the business logic into a new class BusinessLogic and have each class that needs BusinessLogic make calls to the class. If you need a single rooted heirarchy for your classes that make calls to BusinessLogic, you'll have to create an interface as well (BusinessLogicInterface?)

In pseudo-code:

class BusinessLogic 
{
    void method1() { ... }
    void method2() { ... }
}

interface BusinessLogicInterace
{
    void method1();
    void method2();
}

class User 
    extends OtherClass 
    implements BusinessLogicInterface
{
    BusinessLogic logic = new BusinessLogic();

    @Override
    void method1() { logic.method1(); }

    @Override
    void method2() { logic.method1(); }
}

This isn't the prettiest implementation to work around a lack of multiple inheritance and it becomes quite cumbersome when the interface has a lot of methods. Most likely, you'll want to try and redesign your code to avoid needing mixins.

Alex B
ok, so there are no tricks to avoid having to use delegation and invoking logic.method1, logic.method2, logic.method3 explicitly? it would help save on typing and boilerplate code..
joshjdevl
+1  A: 

Is the object-purist stirring in you today?

Think you could do with a little composite oriented programming?

Then you, sir, are looking for Qi4J ;)

Christian Vest Hansen
A: 

QI4J allows you to use mixins

Pablo La Greca