Java如何使用超类方法设置子类标记(字段)
我有课Java如何使用超类方法设置子类标记(字段),java,class,inheritance,methods,Java,Class,Inheritance,Methods,我有课 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
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"));
但是它不起作用。您不能这样做,因为属性
标记
是内部类Jo
的成员,因此只能由外部类Jo
访问。要使子类可以访问属性Tag
,必须删除内部类并添加Tag
属性作为类Jo
的属性。但是,请记住,如果标记
属性声明为:
private String tag; // note tag not Tag with a capital-letter
然后,子类
Js
将无法访问标记
属性。您必须为Jo
中的tag
创建一个setter,该setter可以在Js
@floydian中调用:您的代码工作正常,因此请再次尝试运行它。您应该能够使用add方法设置子类的tag字段,除非该字段标记为private。请参阅oracle文档中的嵌套类教程AFAIK,您不能这样做。我创建了内部类以创建一个数组来保留多个属性。还有其他方法吗?(ArrayList除外)