-1
class Cell {
    Point ob ;
    int distance;
    public Cell(Point x, int i) {
       try {
            ob = x;// works fine
            distance = i;
        } catch (Exception e) {
          System.out.println(e.getStackTrace());

       }
    }

}

class Cell {
    Point ob ;
    int distance;
    public Cell(Point x, int i) {
        try {
            ob.x = x.x; // throws null pointer exception
            ob.y = x.y;
            distance = i;
        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }       

    }

}

Error: I am getting a null pointer exception in the second code. However when I try to just assign the passed object in constructor, it works fine.

3 Answers3

1

In your first example (which works) you are assigning an existing object (passed in by the Point parameter x) to the ob field.

In your second example, you are trying to access a property of ob in order to assign a value to it, however ob never gets assigned to anywhere - it is null, hence the exception.

DigiFriend
  • 1,164
  • 5
  • 10
1

As

ob.x = x.x;

means getting x variable of ob object, you first need to create an instance of Point and assign it to ob.

ob = new Point();

will solve your problem.

sertsedat
  • 3,490
  • 1
  • 25
  • 45
1

You call members on it before you instantiate it.

ob = x;// works fine

here you just assign the variable, but you don't try to use it.

ob.x = x.x; // throws null pointer exception

here you try to set the value of a member of ob, which is an instance of Point. But, you have not yet instantiated the variable, meaning it is, indeed, null.

So, either instantiate it first, or try to access the x variable of the x instance you 've passed as argument.

Stultuske
  • 9,296
  • 1
  • 25
  • 37