I have this interface: public interface MyInterface { void add (int numbers); vo
ID: 3585540 • Letter: I
Question
I have this interface:
public interface MyInterface {
void add (int numbers);
void total();
void countofnumbers();
void mean();
}
how can i implement this interface in a class that DOES NOT use instance variable in order to get the size of the numbers, their total and their mean without using scanners, hash maps, linked lists.
Here add method keeps track of sum and their numbers. Mean can ONLY be calculated when needed.
How do i go about writing the class that implements the interface and the main method please?
Explanation / Answer
Solution=======================
Though you are restricted to use "Instance Variables", I suppose, then you can simply use "class variables" i.e. static variables to do your job.
Whatever variable you need to use, as a part of class, make them static (and use them in that way), so that they becomes "Class Varaibles"
Also, any variables defined inside a method incl main() method, is not an "Instance Variable" as well..
It should roughly look like this:
interface MyInterface {
void add (int numbers);
void total();
void countofnumbers();
void mean();
}
public class NumDum implements MyInterface{
static int size;
static int total;
public NumDum(){
size=0;
total=0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
@Override
public void add(int numbers) {
++size;
total+=numbers;
}
@Override
public void total() {
System.out.println(total);
}
@Override
public void countofnumbers() {
System.out.println(size);
}
@Override
public void mean() {
System.out.println((float)total/size);
}
}
Beware, that since they are now class variables, using multiple objects of this class may lead to unexpected behaviours..