The Official BLOG and Wiki for CustomMode.com
[ start | index | login ]
start > Multiple Inheritance in Java

Multiple Inheritance in Java

Created by dmitry. Last edited by dmitry, 4 years and 50 days ago. Viewed 751 times. #1
[edit] [rdf]
labels
attachments

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

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 NameDescription
Vehicle.javaA non abstract base class that defines method drive()
WaterCraftInterface.javaAn 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.ajAn AspectJ file that defines an implementation of the swim() mothod of the WaterCraftInterface.
Amphibian.javaA 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.javaA 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:

driving...
swimming...
Please login to post a comment.
custommode.com | ©2000-2005
webmaster at custommode dot com