I have a class where arrays are globally declared and public these arrays are initialized though methods in this class. They are not inside of a constructor. I have another class where I have used extends to allow me access to these values. Of course, I am recieving a null pointer exception. How would I go about fixing this? I do not need to override these arrays. JUst need to use them inside of methods to fill other arrays.

I have been at this for awhile now. My experience with java is still pretty minimal. Any suggestions would be appreciated. Thank you everyone

An example of what I am talking about:

public class Parent{
  public double hey[ ];

  public double [] fillHey(){

  hey = new double[57]

  for(int k = 0; k<57; k++)
    {
         hey[k] = k+2;
    }
   }
 }

The child class:

public class Child extends Parent{

public double you[ ];

public double[ ] fillYou(){

you = new double[57];

 for(int k = 0; k<57; k++)
    {
         you[k] = (k+2) * hey[k];
    }
   }
 }
有帮助吗?

解决方案

You did not instantiate hey array in the constructor of either class so it is still null when you use it in the child class.

You can either

  • instantiate it in a constructor

  • or instantiate it inside fillYou() method in the child class (before it's used).

其他提示

If you want to access to the hey[] from the child class, you must call it like this:

double  a[] = super.hey;

Hope it works for you!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top