• Post Reply Bookmark Topic Watch Topic
  • New Topic

why does this program compile?  RSS feed

 
Abigail Decan
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


this program compiles, with a nullpointer exception
i thought it wouldn't compile in the first place because i don't have

"Boxer1 b = " in front of line 9.
 
Barry Burd
Author
Ranch Hand
Posts: 133
10
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can construct a new object without assigning that object to a variable. The call to new Boxer(....) creates a new instance of the Boxer class, which starts doing "x = i + y". The "x = i + y" statement runs into trouble because you haven't made i point to any object. But statements like new Boxer(new Integer(4)); without an assignment to a variable are common in Java.
 
Louis Denning
Ranch Hand
Posts: 64
4
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your NullPointerException seems to be coming from the fact that you're adding y, the parameter of the constructor, to an Integer object, i, that has not been defined (i.e. i was not pointing to anything at the time you tried to add it to y).
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell's rules of thumb about constructors
  • 1: Always write a constructor for every class you write
  • 2: Write as few constructors as you can. If you can get 1 per class, so much the better, but some classes need several constructors
  • 3: Make sure every constructor initialises every instance field
  • No 3 means initialise directly or initialise indirectly, but doing that would have prevented your Exception.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!