This is my code I am experimenting with based on enthuware's
test question:
import java.io.*;
import java.sql.*;
interface I1
{
void m1() throws IOException;
void m2() throws IOException;
}
interface I2
{
void m1() throws SQLException;
void m2() throws FileNotFoundException;
}
public class TestClass implements I1, I2{
public static void main(
String args[]) //throws Exception
{
TestClass tc = new TestClass();
I1 i1 = (I1) tc; //This is valid.
try {
i1.m1();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
i1.m2();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I2 i2 = (I2) tc; //This is valid too.
// i2.m1();
try {
i2.m2();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void m1() throws IOException, SQLException
{
System.out.println("Hi there");
}
public void m2() throws FileNotFoundException
{
System.out.println("How are you?");
}
}
With method m2() I do not get compiler error whereas with m1() I do. So this is my thinking and please correct me if I am wrong:
1) When an interface method declares that it throws an exception the implementing class can throw a narrower exception or not throw an exception at all.
public void m1()
{
System.out.println("Hi there");
}
does not give compiler error.
2) If implementing 2 interfaces with the same method but each one throws a different exception your implementing method can throw a more specific one if the exceptions have a subclass-superclass relationship.
Otherwise you can get a compiler error as is the case here because IOException and SQLException are not compatible with each other.
Your input will be greatly appreciated.
Thanks,
Meera