In Java, an interface is a collection of abstract methods and constant variables. It provides a way to achieve abstraction and define a contract that all implementing classes must follow. An interface does not contain any implementation of methods, only their signatures.
Here is an example Java code to implement the interface concept for finding the sum and average of given N number:
public double getSum(double[] numbers);
public double getAverage(double[] numbers);
}
class MathCalculator implements Calculator {
public double getSum(double[] numbers) {
double sum = 0;
for (double n : numbers) {
sum += n;
}
return sum;
}
public double getAverage(double[] numbers) {
double sum = getSum(numbers);
return sum / numbers.length;
}
}
public class InterfaceExample {
public static void main(String[] args) {
double[] numbers = { 10.5, 20.0, 30.25, 40.75 };
Calculator calculator = new MathCalculator();
double sum = calculator.getSum(numbers);
double average = calculator.getAverage(numbers);
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
}
}
In this example, we define an interface called Calculator with two abstract methods: getSum() and getAverage(). We then define a class called MathCalculator that implements the Calculator interface and provides the implementation for the two methods.
No comments:
Post a Comment
If you have any doubts, please let me know