I come from a C++ background where multiple inheritance is not a problem. Hoewever in Java I'm constrained to use either only class to inherit from or implement an interface. I have multiple classes that already extends another class. But all these classes should share the same debug interface/class. How do I implement such behaviour without duplicating my debug logic multiple times?
Consider my current setup:
public interface Debug
{
public abstract void log();
}
public class ClassA extends AnotherBaseClass implements Debug
{
public boolean doDebug = false;
public void log()
{
if( doDebug )
System.out.println( "LOG" );
}
}
public class ClassB implements Debug
{
public boolean doDebug = false;
public void log()
{
if( doDebug )
System.out.println( "LOG" );
}
}
Typically this is where you use aggregation rather than inheritance, by having the classes have a member (typically private) they use for the debug logging. If the classes have to implement the interface as well as use debug logging internally, then you have them do that and then just hand off each of the Debug interface methods to the private instance.
If you're using Java 8, though, you have another option: see Pablo's answer for default inteface methods, which are kind of Multiple Inheritance Lite.
If you are using Java 8 there is a new feature that addresses your requirement: you can use the reserved word default to provide a default implementation in the interface. This new feature is called default methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With