0

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];
    }
   }
 }
Damien Black
  • 5,579
  • 18
  • 24
handroski
  • 81
  • 2
  • 3
  • 15

2 Answers2

2

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).

Szymon
  • 42,577
  • 16
  • 96
  • 114
1

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!

Fabian Rivera
  • 1,138
  • 7
  • 15
  • I see. Didnt know about .super(). Would I have to change anything else to this code? – handroski Feb 18 '14 at 22:25
  • 1
    Take in count that super refers to the parent class, so, if parent class contains a public X attribute, you can access to it using super.X – Fabian Rivera Feb 18 '14 at 22:28
  • It is the same for calling parent methods and constructors. Nos, with this information, hope you can figure out how to do what you want. – Fabian Rivera Feb 18 '14 at 22:29
  • Thank you. So would I have to instantiate it in a constructor in either class like @Szymon mentioned? – handroski Feb 18 '14 at 22:30
  • 1
    Yeah, I think you must first initialize the array in the constructor you're calling in order to be able to use it. – Fabian Rivera Feb 18 '14 at 22:31