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.
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?