Friday 6 September 2013

Project MI+ | Multiple Inheritance in Java like never before!

 

project mi  logo

Project MI+ add multiple inheritance support to your java classes, so they can (functionally) "extend" (read inherit) from multiple parent classes.

Project MI+ is an open source project published under Apache Public License version 2.0.

Suppose we want to inherit our Child class from two parent classes: (1) ParentOne and (2) ParentTwo.

public class ParentOne {
public void parentOneMethod() {
System.out.println("parent one method");
}
}

public class ParentTwo {
public void parentTwoMethod() {
System.out.println("parent two method");
}
}

First we will 'extract' interfaces from the parent classes mentioned above. [Project MI+ promotes the use of classic design principle 'Program to Interface']

public interface ParentOne {
void parentOneMethod();
}

public interface ParentTwo {
public void parentTwoMethod();
}

public class ParentOneImpl implements ParentOne {
public void parentOneMethod() {
System.out.println("parent one method");
}
}

public class ParentTwoImpl implements ParentTwo {
public void parentTwoMethod() {
System.out.println("parent two method");
}
}

Now we can simply:


  1. Create a Child interface,
  2. Extend it from parent interfaces,
  3. Add "Multiple Inheritance Support" by annotating the Child interface with MISupport (JavaDoc | Source Code) annotation.
import com.smhumayun.mi_plus.MISupport;

@MISupport(parentClasses = {ParentOneImpl.class, ParentTwoImpl.class})
public interface Child extends ParentOne, ParentTwo {
}

For multiple inheritance to work, you should always create new instances of MISupport (JavaDoc | Source Code) annotated classes (only) via MIFactory (JavaDoc | Source Code) instead of directly instantiating them using java's new keyword and a constructor.

import com.smhumayun.mi_plus.MIFactory;

...
MIFactory miFactory = new MIFactory();
Child child = miFactory.newInstance(Child.class);
child.parentOneMethod();
child.parentTwoMethod();
...

The child now refers to an object which (functionally) inherits methods from all the parent classes.

Click here to read more about Project MI+

No comments:

Post a Comment