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.
code:
//something interface
interface something
{
public boolean validate(int value); //methods in interface should
be public to be used in other class
}
//implementing something interface in class Coin
class Coin implements something
{
private int d = 2; // I am considering that diameter is int(i.e 2)
bcoz here we are passing only int
public boolean validate(int value)
{
if(value==d)
{
return true;
}
else
{
return false;
}
}
}
//implementing something interface in class coin
class Available implements something
{
private int a = 3; // I am considering only 3 candies are
Available
public boolean validate(int value)
{
if(value<=a)
{
return true;
}
else
{
return false;
}
}
}
public class Main
{
public static void main(String[] args) {
Coin ob = new Coin();
System.out.println("validating coin
"+ob.validate(4));
Available ob1 =new
Available();
System.out.println("validating
Available "+ob1.validate(2));
}
}
OUTPUT:
B) Polymorphism means nothing but a method can have many different forms. It means a method with same signature can be implemented for different purposes in different ways. Here we used the same method validate for different purposes in different class
Get Answers For Free
Most questions answered within 1 hours.