Java Reference
In-Depth Information
Partially Implementing an Interface
A class agrees to provide an implementation for all abstract methods of the interfaces it implements. However, a class
does not have to provide implementations for all methods. In other words, a class can provide partial implementations
of the implemented interfaces. Recall that an interface is implicitly abstract (means incomplete). If a class does not
provide the full implementation of interfaces, it must be declared abstract (means incomplete). Otherwise, the compiler
will refuse to compile the class. Consider an interface named IABC , which has three methods m1() , m2() , and m3() .
package com.jdojo.interfaces;
public interface IABC {
void m1();
void m2();
void m3();
}
Suppose a class named ABCImpl implements the IABC interface and it does not provide implementations for all
three methods.
package com.jdojo.interfaces;
// A compile-time error
public class ABCImpl implements IABC {
// Provides implementation for only one method of the IABC interface
public void m1() {
// Code for the method goes here
}
}
The above code for the ABCImpl class would not compile. It agrees to provide implementations for all three
methods of the IABC interface. However, the body of the class does not keep the promise. It provides an implementation
for only for one method, m1() . Because the class ABCImpl did not provide implementations for the other two methods
of the IABC interface, the ABCImpl class is incomplete, which must be declared abstract to indicate its incompleteness.
If you attempt to compile the ABCImpl class, the compiler will generate the following errors:
Error(3,14): class com.jdojo.interfaces.ABCImpl should be declared abstract; it does not define
method m2() of interface com.jdojo.interfaces.IABC
Error(3,14): class com.jdojo.interfaces.ABCImpl should be declared abstract; it does not define
method m3() of interface com.jdojo.interfaces.IABC
The compiler error is loud and clear. It states that the ABCImpl class must be declared abstract because it did not
implement the m2() and m3() methods of the IABC interface.
The following snippet of code fixes the compiler error by declaring the class abstract :
package com.jdojo.interfaces;
public abstract class ABCImpl implements IABC {
public void m1() {
// Code for the method goes here
}
}
 
Search WWH ::




Custom Search