如何实例化列表中的对象
我喜欢在文件中搜索begin,如果它找到了,那么就在它后面添加存储代码。下面是示例
public abstract class Structure
{
private List<Structure> structureList = new ArrayList<Structure>();
protected void setStructure(Filemanager file, String line)
{
/*
* set all values at the object structure
*/
line = file.getSourceLine();
while (!line.contains("END_"))
{
if (line.contains("TRANSLATE"))
{
}
else if (line.contains("BEGIN_OBJECT"))
{
structureList.add(new FunctionalStructure(line));
}
else
{
setValue(line);
}
line = file.getSourceLine();
}
}
protected abstract void setValue(String line);
}
public abstract class FunctionalStructure extends Structure
{
private String name;
public FunctionalStructure(String line)
{
super();
this.name = line.substring(line.indexOf("\"")+1, line.lastIndexOf("\""));
}
public String getName()
{
return this.name;
}
public List<Structure> Startfunctional()
{
return null;
}
protected abstract void setValue(String line);
}我在实例化structureList.add(新的FunctionalStructure(行))时遇到问题;
有没有人能说出上面这行出了什么问题?
发布于 2012-06-26 22:51:32
我认为FunctionalStructure必须是一个抽象类(可能是对Structure的扩展)。您不能实例化抽象类。
这就是为什么你会得到这样的错误:
Cannot instantiate the type FunctionalStructure如果您创建了FunctionalStructure类,可能会无意中将其标记为抽象类。假设它实现了setValue(String)方法,您可以从类声明中删除抽象修饰符。
或者,在您正在使用的应用程序接口中使用适当的扩展FunctionalStructure的具体类。
或者,使用匿名内部类:
structureList.add(new FunctionalStructure(line){
public void setValue(String value) {
// your implementation here
}
});发布于 2012-06-26 22:57:07
你可能会发现下面的例子有助于理解这个概念:
package pack;
public class Demo {
public static void main(String[] args) {
MyGeneric<A> obj = new MyGeneric<A>() ;
//obj.add(new C()) ; //don't compile
obj.testMethod(new A()) ; //fine
obj.testMethod(new B()) ; //fine
}
}
class A{}
class C{}
class B extends A{}
class MyGeneric<T>{
public void testMethod(T t) {
}
}编辑:因此,Structure和FunctionalStructure之间必须存在IS-A关系才能成功编译代码。
https://stackoverflow.com/questions/11209913
复制相似问题