0
点赞
收藏
分享

微信扫一扫

java 接口回调

技术只适用于干活 2022-04-05 阅读 82
java

 第一个例子:

package exp_3;

public interface InterfaceA6 {
	int method(int n);
}
package exp_3;

class ClassA implements InterfaceA6{
	public int method(int n) {
		int sum=0;
		for(int i=1; i<=n; i++) {
			sum += i;
		}
		System.out.println(sum);
		return sum;
	}
}

class ClassB implements InterfaceA6{
	public int method(int n) {
		int res =1;
		for(int i=1; i<=n; i++) {
			res *=i;
		}
		System.out.println(res);
		return res;
		
	}
}

public class E6{
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		InterfaceA6 a = new ClassA();
		a.method(5);
		InterfaceA6 b = new ClassB();
		b.method(4);
	}
}

第二个例子:

package exp_3;

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

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class TestCompute {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		UseCompute u = new UseCompute();
		u.useCom(new sum(), 2,1);
		u.useCom(new minus(), 2,1);
		u.useCom(new multiple(), 2,1);
		u.useCom(new divide(), 2,1);
	//	List a =new ArrayList();
		
	}


}

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

class sum implements Compute{
	public int computer(int n, int m) {
		return n+m;
	}
}

class minus implements Compute{
	public int computer(int n, int m) {
		return n-m;
	}
}

class multiple implements Compute{
	public int computer(int n, int m) {
		return n*m;
	}
}

class divide implements Compute{
	public int computer(int n, int m) {
		return n/m;
	}
}
举报

相关推荐

0 条评论