我有一个班级,
public class Jo{
public int objCount = 0;
private int i = 0;
public class Property{
String Tag = new String();
Jo data;
}
public Property propertyArray[] = new Property[12];
public void add(String St, Jo Obj){
propertyArray[objCount] = new Property();
propertyArray[objCount].Tag = St;
propertyArray[objCount].data = Obj;
objCount++;
}
}
和一个子类,
public class Js extends Jo{
String data = new String();
public Js(String St){
this.data = St;
}
}
当我像这样调用add方法时,我需要设置子类的Tag字段。
Jo first = new Jo();
first.add("firsttag", new Js("first string"));
但它不起作用。
答案 0 :(得分:0)
您不能这样做,因为属性Tag
是内部类Jo
的成员,因此只能由外部类Jo
访问。要使属性Tag
可供子类访问,您必须删除内部类并将Tag
属性添加为类Jo
的属性。但是,请记住,如果Tag
属性声明为:
private String tag; // note tag not Tag with a capital-letter
然后,子类tag
将无法访问Js
属性。您必须在tag
中为Jo
创建一个可以在Js
中调用的setter。
答案 1 :(得分:0)
@floydian:您的代码工作正常,因此请再次重试。您应该能够使用add方法设置子类的标记字段,除非该字段标记为私有。请参阅oracle文档以获取嵌套类教程http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html