Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method overriding from multiple interfaces

 
Vivian Josh
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Can someone tell me how to override a method which is in more than one interface and throws different exceptions . How to implement this method in implementor class?

Example:

import java.io.FileNotFoundException;
import java.io.IOException;

interface Parent {
void myMethod(int x) throws IOException;
}

interface Parent2 {
void myMethod(int x) throws ClassCastException;
}

public class ObjectTest implements Parent, Parent2 {

public void myMethod(int x) throws IOException{
System.out.println("Child");
}

public void myMethod(int x) throws ClassCastException{
System.out.println("Child");
}

public static void main(String args[]) {
Parent ot = new ObjectTest();
try {
ot.myMethod(2);
} catch (IOException e) {

e.printStackTrace();
}
}


The above code gives error at both method implementation.

If I implement method once and add both throws, still it gives error.

What should be done to implement such methods?

Thanks,
Vivian
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This works:

A subclass should be able to be used in anywhere its superclass can be used. (See "Liskov Substitution Principle"). In this case any code that uses a Parent2 reference expects to be able to call myMethod(int) without having to handle an IOException. Your subclass method can't be more restrictive than the method it is overriding. It can however be less restrictive and throw fewer checked Exceptions than the method that it is overriding.
[ July 02, 2007: Message edited by: Garrett Rowe ]
 
Vivian Josh
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Garrett !

Does this mean we can not use throws clause with implementor class where same method is used in multiple interfaces with different exceptions?

What if developer wants to use more restrictive checked exceptions on the method?
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does this mean we can not use throws clause with implementor class where same method is used in multiple interfaces with different exceptions?
Thats correct.

What if developer wants to use more restrictive checked exceptions on the method?
That is simply not allowed in Java.
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sliding back to scjp
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic