Exceptions and inheritance

Hi all,

I need some help to solve a design problem ( I suppose !).

I磛e created an Interface declaring methods that throws an Exception and created an Adapter implementing my Interface.

I thought that when I write a class that extends my Adapter it would force to write the method signature with the throws declaration, what it doesn磘.

Well, what I want is when someone write a class, it should extends/implements my Adapter/Interface and the overridden method should have the throws declaration.

I don磘 know if I was clear, but if so, is there any way to implement this design ?

Here is how is my classes:

publicinterface MyInterface{

publicboolean MyMethod(Object o)throws MyException ;

}

publicabstractclass MyAdapterimplements MyInterface{

publicboolean MyMethod(Object o)throws MyException{

returnfalse;

}

}

publicclass MyClassextends MyAdapter{

publicboolean MyMethod(Object o){

returnfalse;

}

}

I磀 like to force MyMethod at MyClass to throw MyException !

Thank you

[2072 byte] By [aboaventuraa] at [2007-10-3 0:15:49]
# 1

You can throw fewer checked exceptions in subclass, but you can't throw more than the superclass.

The idea is that your implementation in the subclass might decide to handle the checked exception, which is perfectly OK.

It's called the Liskov Substitution Principle: If class B is a subclass of A, then you've got to be able to use class B in every situation when class A is called for.

I don't know of a way to ask the JVM to enforce it, since not throwing the checked exception in the subclass is legal.

You can enforce such a thing with reflection or aspect oriented programming.

%

duffymoa at 2007-7-14 17:06:29 > top of Java-index,Other Topics,Patterns & OO Design...
# 2
Thank you Duff.I didn磘 attempted for that aspect of inheritance. I believe I have to study much more !
aboaventuraa at 2007-7-14 17:06:29 > top of Java-index,Other Topics,Patterns & OO Design...
# 3

It should not matter what the implementors do. If they have no reason to throw the exception then they will not.

However, the users of your interface will have to catch the exception no matter what the implementors are doing. For instance

MyInterface mi = new MyClass();

try {

mi.MyMethod(new Object());

}

catch(MyException me){

me.printStackTrace();

}

MyClass does not actually throw the exception but the caller of MyMethod must catch it anyway.

_dnoyeBa at 2007-7-14 17:06:29 > top of Java-index,Other Topics,Patterns & OO Design...
# 4
Not if it's an unchecked exception.%
duffymoa at 2007-7-14 17:06:29 > top of Java-index,Other Topics,Patterns & OO Design...