Consider the following interface:
interface Something
{
boolean validate(int value);
}
Classes that implement “Something” interface can validate a specific value in different behaviors within some context. For example, this interface could be useful to program a candy dispenser machine to check whether the coin inserted is a valid coin such as a quarter with a diameter of 2.426 centimeters. Also, it could be useful to check if there is any candy available to dispense.
Here is the code to the given question.
(a)
Here are two classes Coin.java and Available.java that implement "Something" interface.
Coin.java
public class Coin implements Something {
@Override
public boolean validate(int diameter) { //function that overrides validate function of "Something" interface
if(diameter>2){ //check if the diameter is greater than 2cm
return true;
}
else{
return false;
}
}
}
Available.java
public class Available implements Something {
@Override
public boolean validate(int numOfCandies) { //function that overrides validate function of "Something" interface
if(numOfCandies>0){ //check if number of candies are greater than 0
return true;
}
else{
return false;
}
}
}
(b)
In the above example the method 'validate' in 'Something' interface is used in two different classes that implement it.In the case of Coin class, this method is used to check if the coin is valid by checking if the diameter is greater than a certain value.The parameter that is sent to this function in this case is the diameter of the coin.
In the case of Available class, this method is used to check if there are any candies available in the machine by checking if the number of candies in the machine is greater than 0.The parameter that is sent to this function in this case is the number of candies.
In the above two implementations, we have seen how one function can be differetly reused in different classes.
This is one of the classic examples of polymorphism.With the help of this, we can write a generic code in one class ( method signature in this case) and various other classes can implement it by giving their own implementations ( in this case, the method 'validate' is implemented in different ways by two classes).
Another major advantage is that if we want to modify any code in any of the child classes , we can modify it without modifying the parent class.
Also, the above example helps in code-reuse because if we need any new implementation of the given method, we can just implement the interface and add our own method implementation to it. In this case,if we want any new implementation of the method 'validate', we can create a new class that implements this interface and give this method its own implementation.
Get Answers For Free
Most questions answered within 1 hours.