Java如何使用超类方法设置子类标记(字段)

时间:2013-12-01 11:00:56

标签: 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 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"));

但它不起作用。

2 个答案:

答案 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