AhmetSinav
AhmetSinav

Reputation: 55

using class as array in another class

I am trying to do the following

1 - I need to create a class like this

public class base {
    int a;
    String b;
    public base() {
      a = 0;
      b = "";
    }
}

2 - I need to create a class that creates an array of "base" and sets some values

public class arrayBase {
    public base[] ab = new base[2];    
    public arrayBase() {  
       ab[0].a = 1;
       ab[0].b = "test1";
       ab[1].a = 2;
       ab[1].b = "test2";       
    }
}

3 - I need to use "arrayBase" in another class

public class test{
    public static void main(String[] args) {
       arrayBase p = new arrayBase();
       System.out.println(p.ab[0].a);
    }
}

When I try this it gives an error

Exception in thread "main" java.lang.NullPointerException.

How can I solve that problem?

Upvotes: 0

Views: 106

Answers (3)

Vincenzo Maggio
Vincenzo Maggio

Reputation: 3869

The problem is this line:

 public base[] ab = new base[2]; 

Here you are simply reserving heap space for two base objects, but you still need to create them and assign them to the correct array cell, like this:

  public class arrayBase{
    public base[] ab = new base[2];    
    public arrayBase() {  
       ab[0] = new base();
       ab[0].a = 1;
       ab[0].b = "test1";

       ab[1] = new base();
       ab[1].a = 2;
       ab[1].b = "test2";       
    }
  }

And please, name your class Base instead of base!

Upvotes: 2

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32468

Modify the arraBase constructor as bellow. Problem there is, there are no object in the ab array, but, you try to access declared object's fields. First, you need to populate the arra with declared objects, then assign the value for the fields of those objects. And, Fix the compilation errors

public arrayBase() {  
     ab[0] = new base();
     ab[1] = new base()
     ab[0].a = 1;
     ab[0].b = "test1";
     ab[1].a = 2;
     ab[1].b = "test2";       
    }

Upvotes: 1

Mason T.
Mason T.

Reputation: 1577

For a recommendation,

  public class arrayBase{
  public base[] ab = new base[2];    
  public arrayBase() {  
     ab[0] = new base();
     ab[1] = new base();
     ab[0].a = 1;
     ab[0].b = "test1";
     ab[1].a = 2;
     ab[1].b = "test2";       
    }
  }

The class base needs to be intialized, also remember that you can only change the variable a and b if the base class is in the same package because of the default protected modifier.

Upvotes: 1

Related Questions