write a java code Part I: Write an interface called Calculatable that has a meth
ID: 3893347 • Letter: W
Question
write a java code
Part I:
Write an interface called Calculatable that has a method called calculate that accepts an integer as a parameter and returns a double based on some calculations that are done with data members and the integer parameter.
public interface Calculatable
{
double calculate(int i);
}
Define at least two classes that implement Calculatable and have different calculate methods.
Create objects and call calculate on each one. Print out the output of these method calls.
Part II:
Create a public class with two methods.
A main method. Create an array of Calculatable objects in main and call the sumCalculate method with the array and an integer of your choice. You can define the array as follows:
Calculatable [] calcOb;
A method called sumCalculate that accepts an array of Calculatable objects and an integer parameter x. It should return the sum of the values that are returned by each object's call to its calculate method with the same parameter x.
double sumCalculate(Calculatable [] array, int x)
Realize that even though it's not possible to make instances of an interface (like Calculatable), it is possible to have a reference of type Calculatable and then assign an object to the reference. Of course, the object must be of a type that implements the Calculatable interface.
Explanation / Answer
Calculatable.java
public interface Calculatable {
double calculate(int i);
}
_____________
ClasOne.java
public class ClasOne implements Calculatable {
@Override
public double calculate(int i) {
return i*1.5;
}
}
_______________
ClasTwo.java
public class ClasTwo implements Calculatable {
@Override
public double calculate(int i) {
return i*2.5;
}
}
______________
Test.java
public class Test {
public static void main(String[] args) {
Calculatable [] calcOb={new ClasOne(),new ClasOne(),new ClasTwo(),new ClasTwo()};
int x=5;
double sum=sumCalculate(calcOb,x);
System.out.println("Sum is :"+sum);
}
private static double sumCalculate(Calculatable[] calcOb, int x) {
double sum=0;
for(int i=0;i<calcOb.length;i++)
{
sum+=calcOb[i].calculate(x);
}
return sum;
}
}
________________
Output:
Sum is :40.0
_______________Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.