修改子类中的类数组

时间:2015-02-15 09:01:26

标签: java arrays class inheritance

Dog类的大小为3的数组,包含四个字符串值。但是,在子类GreatDane中,我必须向同一个数组添加一个元素。我必须在不使用arraylist的情况下这样做(我的Java课程还没有涵盖那些)。

这是班级:

abstract class Dog {

String mSize [] = {"tiny", "small", "average", "large"};

int mFeedCounter;

int dogSize = 0;

String getSize() {
        return mSize[dogSize];
    }

    /*
     * setSize
     * Sets the size of the Dog
     * @param size the new size of the Dog, a String
     * @return nothing
     */
    void setSize(String size) {
        mSize[dogSize] = size;
    }

这是子类:

Define the GreatDane class below
 *
 *  Great Danes have an extra size category, "huge".
 *  After growing to a "large" size, they may grow
 *  to an additional, "huge" size after 3 meals.
/************************************************/
class GreatDane extends Dog{
      String mSize[] = {"tiny","small","average","large","huge"};

    @Override
    void feed(){
        if(++mFeedCounter == 3){
        dogSize ++;
        getSize();
        mFeedCounter = 0;}
      }
    }

我尝试使用mSize = new String []{"tiny","small","average","large","huge"};重新分配数组引用,但这只是给了我一个标识符预期错误。

无论如何,我不知道为什么GreatDane没有搬到mSize[4]

作为参考,这是另一个具有类似方法的类:

class Chihuahua extends Dog{
    @Override
    void feed(){
        if(++mFeedCounter ==5){
        dogSize++;
        getSize();
        mFeedCounter = 0;}
    }
}

2 个答案:

答案 0 :(得分:0)

在你的GreateDane构造函数中,你可以改变Super的mSize的引用,如下所示:

GreatDane() {
    String mSize[] = new String[5];//define string array of size 5
    System.arraycopy(super.mSize, 0, mSize, 0, super.mSize.length);//copy existing elements from parent class
    mSize[4] = "huge";//add new elements at the end
    super.mSize = mSize;//change reference of super now as you dont want two copies of the same array in parent and child.
}

答案 1 :(得分:0)

首先,如果你希望你的子类能够修改mSize所引用的数组,那么如果你希望你的子类能够修改mSize所引用的数组,那么你应该声明protected访问权限,而不是包装 - 私人(默认)访问:

protected String[] mSize = {"tiny", "small", "average", "large"}; //Brackets are idiomatically placed after type, not name, in Java.

You can read more about access modifiers here.然后,所有子类(不仅仅是同一个包中的子类)都可以修改它。您的尝试无效,因为它会创建一个新变量mSize,恰好与Dog的{​​{1}}同名,但完全不同。由于您在班级mSize中定义了getSize(),因此它指的是Dog的{​​{1}},而不是Dog的{​​{1}}。相反,使用mSize重新分配是正确的,但是您收到错误,因为您不能简单地将代码语句放在任何地方。您需要将语句放在构造函数中:

GreatDane

或在初始化程序块中:

mSize

很难说哪个版本更正确,因为这个设计首先没有意义。理论上,mSize = new String [] {"tiny","small","average","large","huge"};应该替换为引用//these classes and methods should be public (also in Dog) public class GreatDane extends Dog { public GreatDane() { mSize = new String[]{"tiny","small","average","large","huge"}; } @Override public void feed(){ mFeedCounter++;//incrementing inside other statements is concise but discouraged if (mFeedCounter == 3) { //consider >= 3 just in case dogSize++; getSize(); mFeedCounter = 0; } } } 数组的getSizeDescription方法,并且在描述其他大小的类中被覆盖,或者支持所有可能的大小,但禁止使用错误类型的狗从增长过大。