当前位置:网站首页>2. interface (calculator)

2. interface (calculator)

2022-06-22 23:17:00 Xiaomurong

2 Interface
Using the interface as a parameter , Complete a calculator , Can complete addition, subtraction, multiplication and division .
(1) Define an interface Compute It contains a method int computer(int n, int m).
(2) Design four classes to implement this interface , Complete addition, subtraction, multiplication and division .
(3) Design a class UseCompute, Class contains methods :public void useCom(Compute com, int one, int two), This method can be called with the passed object computer Method to complete the operation , And output the result of the operation .
(4) Design a main class Test, call UseCompute The method in useCom To complete the addition, subtraction, multiplication, and division operations .

interface Compute {
    
	int computer(int n, int m);
}

class Add implements Compute {
    

	@Override
	public int computer(int n, int m) {
    
		// TODO Auto-generated method stub
		return n + m;
	}

}

class Sub implements Compute {
    

	@Override
	public int computer(int n, int m) {
    
		// TODO Auto-generated method stub
		return n - m;
	}

}

class Mul implements Compute {
    

	@Override
	public int computer(int n, int m) {
    
		// TODO Auto-generated method stub
		return n * m;
	}

}

class Div implements Compute {
    

	@Override
	public int computer(int n, int m) {
    
		// TODO Auto-generated method stub
		return n / m;
	}

}

class UseCompute {
    
	public void useCom(Compute com, int one, int two) {
    
		System.out.println(com.computer(one, two));
	}
}

public class Test {
    
	public static void main(String[] args) {
    
		UseCompute uc = new UseCompute();
		uc.useCom(new Add(), 4, 2);
		uc.useCom(new Sub(), 4, 2);
		uc.useCom(new Mul(), 4, 2);
		uc.useCom(new Div(), 4, 2);
	}
}
原网站

版权声明
本文为[Xiaomurong]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221502449101.html