开发者

Java, filling arrays, and inheritance

I think I'm running into an inheritance conceptual wall with my Java arrays. I'm kind of new to Java so please tell me if I have things upside down. In essence, I want to do three things:

  1. Create a runnersArray with the attributes of my Runners class.
  2. Fill my runnersArray using my GenerateObjects method of my GenerateObjects class.
  3. Access the contents of my filled runnersArray in my Evaluating method of my Evaluating class.

The problem seems to be that runnersArray is not visible to the methods in steps 2 and 3 above, but their classes (due to design reasons) cannot inherit or extend Runners class.

Thanks in advance for any suggestions.

Here are some code snippets showing what I'm trying to do:

public class Runners extends Party {

    Runners[] runnersArray = new Runners[5];
}

and

public class GenerateObject extends /* certain parent class */ {

     public GenerateObject (int arrayNum) {
          runn开发者_高级运维ersArray[arrayNum] = /* certain Runners attributes */;
     }
}

and

public class Evaluating extends /*certain parent class*/ {

     public Evaluating (int arrayNum) {
          System.out.println(/* String cast attribute of runnersArray[arrayNum]*/;
     }
}


The way you have it in your code sample, runnersArray is a package-private (because it doesn't have any access specifier, default is package-private) instance variable of the Runners class. So you cannot just access it from within the GenerateObject and Evaluating classes.

If you want runnersArray to be a globally visible object, then perhaps it should be a public static variable.

public class Runners extends Party {
    public static Runners[] runnersArray = new Runners[5];
}

Then you can access it from the other classes like this:

public class GenerateObject extends /* certain parent class */ {
    public GenerateObject (int arrayNum) {
        Runners.runnersArray[arrayNum] = /* certain Runners attributes */;
    }
}

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜