Interface-calculator and interface Calculator

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.