![](/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.