I always thought that two interfaces with the same method cannot be inherited by one class, as stated in many so questions.
Java jre 7, jdk 1.7
But this code here is working.
Example:
Interfaces:
public interface IObject
{
public Object create(Object object) throws ExceptionInherit;
}
public interface IGeneric<T>
{
public T create(T t) throws ExceptionSuper;
}
Implementing class:
public class Test implements IGeneric<Object>, IObject
{
@Override
public Object create(final Object object) throws ExceptionInherit
{
return object;
}
}
Don’t those two method declarations have the same body?
Exceptions:
The exceptions are just additive to this construct making it more complex.
public class ExceptionSuper extends Exception {}
public class ExceptionInherit extends ExceptionSuper {}
It works without any thrown exceptions too.
Further: If both methods interfaces throw different inheriting exceptions i could cast UserLogic to any of the two interfaces and retrieve a different subset of the exceptions!
Why is this working?
Edit:
The generic implementation is not even necessary:
public interface IA
{
public void print(String arg);
}
public interface IB
{
public void print(String arg);
}
public class Test implements IA, IB
{
@Override
public void print(String arg);
{
// print arg
}
}
You can definitely “implement” two interfaces that have methods of the same signatures. You get into trouble trying to “extend” two classes that have identical method implementations. Multiple-interface inheritance is GOOD; multiple-implementation inheritance is TRICKY.
An “ExceptionInherit” object can be used in place of an “ExceptionSuper” object because it inherits from it. The “ExceptionInherit” object has all the information that the “ExceptionSuper” object does (plus more). This is not true the other way around. You can’t use an “ExceptionSuper” object in place of “ExceptionInherit” object because the “ExceptionInherit” code expects more than your base object has (well, potentially but not in your case).
Your implementation of the “create” method fills the ICreateUser “create” signature because it throws an “ExceptionInherit” which can be thrown to catchers of both “ExceptionInherit” and “ExceptionSuper” get all the information they need (just the base class) from the object.
You couldn’t change your implementation to throw an “ExceptionSuper” because catchers expecting a “ExceptionInherit” would get an object with not enough information.