• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubts in Interface  RSS feed

 
Kathiresan Chinnasamy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends,

Just Look the sample code and tell me answer

1. INTERFACE

public interface Inter1 {

void func1()throws IOException ;

}

2. CLASS
public class Imple implements Inter1 {

public void func1() { // here i haven't throws IOException but i // mentioned in Inter1 ... its running successfully

System.out.println("Hi.....");
}
}


The Above examples running successfully without throws IOExcetion in Imple class? why and how?
 
Brij Garg
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
running successfully .. i doubt.
there is no main method.


1. INTERFACE

public interface Inter1 {

void func1()throws IOException ;

}

2. CLASS
public class Imple implements Inter1 {

public void func1() { // here i haven't throws IOException but i // mentioned in Inter1 ... its running successfully

System.out.println("Hi.....");
}
}


This code will compile because we are free to throw no exception, any runtime exception or narrow exception or same exception while overriding.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An implementation of a interface may choose not to throw all the exceptions defined by the interface.
However, one can not add a new exception to the throws clause that does not appear in the interface definition.

The reason being:

A client using the interface would not be aware of the implementation. What he/she will know that the method "may" throw an exception. It does not hurt if the implementation does not throw it. After all, exceptions are for error conditions!

On the other hand, if the implementation adds an exception to the throws clause, the client will never be able to know that there is some other error that he/she needs to handle.
 
Kathiresan Chinnasamy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it

Thank you bittoo garg and Nitesh Kant ...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!