Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
What happens if a class doesn't implement all the methods defined in the interface?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ: What happens if a class doesn't implement all the methods defined in the interface?

What happens if a class doesn't implement all the methods defined in the interface?

When a class is defined to implement an interface, the class must provide definitions of all the methods defined in the interface. Otherwise, you will get compiler time error.

A class must implement all methods of the interface, unless the class is declared as abstract. There are only two choices:

  • Implement every method defined by the interface.
  • Declare the class as an abstract class, as a result, forces you to subclass the class (and implement the missing methods) before you can create any objects.

The only case the class do not need to implement all methods in the interface is when any class in its inheritance tree has already provided concrete (i.e., non-abstract) method implementations then the subclass is under no obligation to re-implement those methods. The supclass may not implement the interface at all and just method signature is matched. For example,

interface MyInterface {	 
  void m() throws NullPointerException;
} 

class SuperClass {//NOTE : SuperClass class doesn't implements MyInterface interface 
  public void m() {
    System.out.println("Inside SuperClass m()");
  }
}

class SubClass extends SuperClass implements MyInterface {
}

public class Program {  
  public static void main(String args[]) {
    SubClass s = new SubClass();
    s.m();
  }
}

The above code shows a concrete class SubClass that declares that it implements an interface MyInterface, but doesn't implement the m() method of the interface. The code is legal because its parent class SuperClass implements a method called m() with the same name as the method in the interface.


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help