Question

Consider the following interface: interface Something {     boolean validate(int value); } Classes that implement “Something”...

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.

  1. Write two classes “Coin” and “Available” that implements “Something” interface to serve the explained purposes. Hint: the variable “value”, treated as the diameter of the coin in the “Coin” class, and treated as the number of available candies in the “Available” class.
  2. Explain in your own words how this exercise helped you understand polymorphism and code-reuse concepts.

Homework Answers

Answer #1

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

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT