Ways to address multiple inheritance in java
- Implementing multiple Interfaces
- Implementing multiple Interfaces delegating work to concrete classes immplementations
- Using Inner Classes
- Using marker interface
- Using Generics
- Using AOP
This is the true multiple inheritance (MI) implementation in
java that does not have the weaknesses of the other solutions and works almost like MI in C++. It's very simple. The example code consists of:
| File Name | Description |
|---|
| Vehicle.java | A non abstract base class that defines method drive() |
| WaterCraftInterface.java | An interface that declares swim() method. Actually it does not even have to declare the swim() method since the implementation will be provided by the aspect (see below). It just makes it more explicit if it is declared, but if the programmers consider it redundunt it can be ommited. |
| WaterCraftAspect.aj | An AspectJ file that defines an implementation of the swim() mothod of the WaterCraftInterface. |
| Amphibian.java | A class that extends from Vehicle and implements WaterCraftInterface. The implementation of the swim() method is dynamically injected, so the programmer does not have to write it for every class that implements WaterCraftInterface. |
| AmphibianTest.java | A JUnit test that demonstrates the use of Amphibian class . |
See code below:Vehicle.java
package com.custommode.aop;/**
* @author damelchenko
*
*/
public class Vehicle { public void drive() {
System.out.println("driving...");
}} WaterCraftInterface.java
package com.custommode.aop;/**
* @author damelchenko
*
*/
public interface WaterCraftInterface {
public void swim();
} WaterCraftAspect.aj
package com.custommode.aop;
/**
* @author damelchenko
*
*/
public aspect WaterCraftAspect {
public void WaterCraftInterface.swim() {
System.out.println("swimming...");
}
} Amphibian.java
package com.custommode.aop;
/**
* @author damelchenko
*/
public class Amphibian extends Vehicle implements WaterCraftInterface {
} AmphibianTest.java
package com.custommode.aop;import junit.framework.TestCase;/**
* @author damelchenko
*/
public class AmphibianTest extends TestCase { Amphibian amphibian = new Amphibian();
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
} public void testDrive() {
amphibian.drive();
amphibian.swim();
}} Results of running AmphibianTest.java: