Java Reference
In-Depth Information
Use a general rule of thumb to check if adding or dropping a constraint is allowed in a class method, which
overrides an interface's method. Write code using an interface type variable that is assigned an object of the class that
implements the interface. If the code makes sense to you (of course, it has to make sense to the compiler too), it is
allowed. Otherwise, it is not allowed. suppose J is an interface, which declares a method m1() , suppose the class C
implements the interface J and it modifies the declaration of the method m1() . If the following code makes sense and
compiles, the modification in the m1() declaration inside the class C is fine.
Tip
J obj = new C(); // Or any object of any subclass of C
obj.m1();
another rule of thumb is to see if the overriding method in the class is relaxing the restrictions declared in the interface
for the same method. If an overriding method relaxes the constraints of the overridden method, it is fine. Otherwise,
the compiler will generate an error.
Implementing Multiple Interfaces
A class can implement multiple interfaces. All interfaces that a class implements are listed after the keyword
implements in the class declaration. Interface names in the list are separated by a comma. By implementing multiple
interfaces, the class agrees to provide the implementation for all abstract methods in all interfaces. Suppose there are
two interfaces called Adder and Subtractor , declared as follows:
public interface Adder {
int add(int n1, int n2);
}
public interface Subtractor {
int subtract(int n1, int n2);
}
If an ArithOps class implements the two interfaces, its declaration would look as shown:
public class ArithOps implements Adder, Subtractor {
// Override the add() method of the Adder interface
public int add(int n1, n2) {
return n1 + n2;
}
// Override the subtract() method of the Subtractor interface
public int subtract(int n1, n2) {
return n1 - n2;
}
// Other code for the class goes here
}
 
 
Search WWH ::




Custom Search