开发者

how do I make an array of new objects that implement a common interface in java

This is how I'm trying to do it:

interface a{} 
class b implements a{
    a[] array; 
    new b(){
        array={ new aImplementer(), new aImplementer(), new aImplementer()}; 
    } 
} 

Why can't I do this? Am开发者_如何学运维 I just doing it wrong? Right now the error I'm getting is an illegal start of expression error at the { part of array={


Your syntax is off. I believe you want something like this (Final revision--actually tested this time--then redone after my changes were overridden.)

interface A{} 

class AImplementer implements A{};

class B { 
    A[] array; 
    B(){  
        array=new A[]{ new AImplementer(), new AImplementer(), new AImplementer()}; 
    } 
 }

There, guaranteed to compile or twice your money back :)

Also threw in "classes should start with an upper case letter" for no charge.


You can only assign an array to an array literal (I'm not sure what you call these beasts) at declaration of the variable. So this may be OK

// array literal assigned at variable declaration
a[] array = { new aImplementer(), new aImplementer(), new aImplementer()};  
new b(){

} 

But what you have where you declare it first and then assign it at a different spot isn't OK. Why? I'm not sure other than that's how it is in the JLS.

Edit: Updated compiled/tested code:

interface A {
}

class AImplementer implements A {
};

class B {
   A[] array = {new AImplementer(), new AImplementer(), new AImplementer()};

   B() {

   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜