![](/img/trans.png)
[英]How to define different required methods in this Java program of array manipulation?
[英]in Java, how do I define different methods for an interface array? Using hash tables without java library
我在Java中有一个编程问题:
我可以为任何不同的接口数组元素定义不同的方法吗?
myInterface[] op = new myInterface[4];
现在,“ myInterface”只有一种方法: public static int doSomething(int a, int b);
。
我需要定义该方法以根据元素ID(0-3)对数字进行不同的处理。
限制条件:
例如,如果我调用op[0].doSomething(2,3)
它将输出12
(2 ^ 2 * 3)
如果我调用op[1].doSomething(2,3)
它将输出5
(2 + 3)。
编辑:我想知道是否有可能还是我在追逐我的尾巴?
如果有人可以提出建议的解决方法,那么我不需要整个答案,而只是建议。
PS另外,我查看了Java接口上的所有页面,但没有发现任何帮助。
我知道了。
class interface operations { public int doSomething(int a, int b) {} }
public class test {
public static void main(...) {
operations[] ops = new operations[4];
ops[0] = new operations() {public int doSomething(int a, int b) {return a-b*a;}};
...etc.
}
答:使用匿名类。
我会用这种方法
public class MyInterface{
private int numberInStack;
public MyInterface(int num){
this.numberInStack = num;
}
public static int doSomething(int a, int b){
switch (numberInStack):
case 0: {
return a-b*a;
}
//... all other cases
}
然后在代码中
MyInterface[] op = new MyInterface[4];
op[0] = new MyInterface(0);
但是,这表明doSomething
实际可以做的事情数量可观且合理,并且实际上它将始终返回int
。 我会以其他方式在第一个答案中使用该方法
我认为在有效Java的第2章中,最重要的是在第33章(EnumMap)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.