在下面的代码中,我提供了两个主要类 - TestWorks 和 TestCompilesButFails。我不确定我理解这个失败的原因 - 似乎 Arrays.asList() 表达式被给定类型“List of AbstractBaseClass”,但为什么在这里给出引用另一个包中的包本地类的类型是正确的呢?
// failing test class
import somepackage.*;
import java.util.Arrays;
public class TestCompilesButFails {
public static void main(String [] args){
// fails here with java.lang.IllegalAccessError:
// tried to access class somepackage.AbstractBaseClass
// from class TestCompilesButFails
for (Object o : Arrays.asList(new ConcreteA(), new ConcreteB())) {
System.out.println(o);
}
}
}
// package-local abstract base class
package somepackage;
abstract class AbstractBaseClass {
public abstract void doSomething();
}
// next two classes - public extenders of abstract base class
package somepackage;
public class ConcreteA extends AbstractBaseClass {
public void doSomething(){
System.out.print("Look, ma!\n");
}
}
package somepackage;
public class ConcreteB extends AbstractBaseClass {
public void doSomething(){
System.out.print("No types!\n");
}
}
// working test
import somepackage.*;
public class TestWorks {
public static void main(String [] args){
new ConcreteA().doSomething();
new ConcreteB().doSomething();
}
}