Interface-calculator and interface Calculator
Using Interfaces for parameters, write a calculator to complete +-*/operations
(1) define an interface Compute containing a method int computer (int n, int m );
(2) design four classes to implement this interface respectively and complete the +-*/Operation
(3) Design a class UseCompute with the following methods: public void useCom (Compute com, int one, int two)
This method requires that: 1. Use the passed object to call the computer Method to complete the operation. 2. output the operation result.
(4) Design a test class and call the useCom method in UseCompute to complete the +-*/operation.
1 public interface Compute {2 3 int computer(int m,int n);4 5 }
1 public class Add implements Compute {2 3 @Override4 public int computer(int m, int n) {5 6 return m+n;7 }8 9 }
1 public class Subtract implements Compute {2 3 @Override4 public int computer(int m, int n){5 6 return m-n;7 }8 9 }
1 public class Cheng implements Compute {2 3 @Override4 public int computer(int m, int n){5 6 return m*n;7 }8 9 }
1 public class Chu implements Compute {2 3 @Override4 public int computer(int m, int n) {5 6 return m/n;7 }8 9 }
1 public class UseCompute {2 public void useCom (Compute com, int one, int two) {3 4 com. computer (one, two); 5 System. out. println ("result =" + com. computer (one, two); 6 7} 8 9 public static void main (String [] args) {10 11 UseCompute jsq = new UseCompute (); 12 // Add 13 Add a = new Add (); 14 jsq. useCom (a, 150, 33); 15 // minus 16 Subtract B = new Subtract (); 17 jsq. useCom (B, 150, 33); 18 // multiply 19 Cheng c1 = new Cheng (); 20 jsq. useCom (c1, 150, 33); 21 // except 22 Chu c2 = new Chu (); 23 jsq. useCom (c2, 150, 33); 24} 25}
Result: