0

I am using NetBeans IDE for swings programming

This is a Add/Edit scenario, MyFrame1 handles MyClass1 obj and MyClass1 has MyClass2, if a MyClass2 has to be add/edit present in MyClass1 MyFrame1 launches MyFrame2

I tried using the following code and got NullPointerException

class MyFrame2 extends JFrame implements ActionListener{
  MyFrame1 parent;
  MyClass2 obj;
  Test(MyFrame1 parent){ // For Add scenario
     //this.parent = parent
     obj = new MyClass2();
     //do something
  }
  Test(MyFrame1 parent, MyClass2 obj){ // For Edit scenario
     //this.parent = parent 
     this.obj = obj;
     //do something
  }
  //functions
  ........
  private void foo(){
     parent.addValues(obj); //throws NullPointerException
  }

  //some editor managed code and fields
  ............

  {
     this.parent = parent; 
     //other initalizations
  }
}

As far as I know the

  1. initializing block code is copied to the beginning of every constructor

  2. initializing a field inside initializing block, the declaration of the field should present before the initializing block.

Then why I am getting NullPointerException when I include this.parent = parent; in initializing block and works fine if directly added to the constructors?

Is initializing block code not copied to the constructor?

Sab
  • 485
  • 5
  • 17
  • 1
    cant see anywhere in `MyFrame2` an assignment on `this.parent` , except of the initializing block , which will be definitely null , so when you uncomment it from the constructor , it will work fine – AntJavaDev May 03 '16 at 13:42
  • 1
    `class MyFrame2 extends JFrame` That seems less than optimal on 2 counts: 1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) Prefer composition over inheritance when it comes to frames and panels. – Andrew Thompson May 03 '16 at 13:46
  • remove the commented lines inside your constructor `this.parent = parent;` – Priyamal May 03 '16 at 13:48
  • @AndrewThompson Thanks for the link and I could use more of that kind – Sab May 03 '16 at 13:57

3 Answers3

0

You are initializing a parent with null.

This

 {
     this.parent = parent; 
     //other initalizations
 }

is the same as

 MyFrame1 parent = null;
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
0

It is possible that you are calling the foo method before you call any of the Test methods, at that point obj would have no reference (would be null), causing the NullPointerException, may I suggest making the "Test" methods constructors to avoid this? they seem to serve the porpouse of initializing values anyway

0

What you are calling initializing block is in really an static initializing block that is called before the constructor and before an instance of MyFrame2 is created.

Learn about static initializing blocks here: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

tak3shi
  • 2,305
  • 1
  • 20
  • 33