Forums Register Login

Null Pointer Exception: constructors dilemma

+Pie Number of slices to send: Send
I was just going through java questions in Facebook group for Java and found below code throwing null pointer Exception. I gave an explanation below. However i want to make sure i have given correct explaination. So please review it and let me know so that i can convey the same




can anyone explain
why jvm throw NullPointerException?



My Explaination:

That is because you are recraeting instance of class A and this is not set to reference of A in class B. here is the flow of your program
1. Created instance of A in main()
2. call m1();
3. Inside m1(), created instance of Class B.
4. call m2(CURRENT instance of A)
5. set this insatnce of A to A's reference valraible a
6. Sysout and exit m2.
7. sysut in m1() and exit m1() and come back to main method
8. Create instance of B( which calls uper class constructoer and create new instance of A)
9. call m3();
10. Now m3 dont have instance of A set in a, a is null, so throw Null Pointer Exception.
11. Now how do we solve it: just call m3 with refernce var a holding instanceof A actualy,
This can be done by calling m3("msg") from m2(); and comment b.m3("prince") from main method or pass instance of A to m3() and set it to ref variable a in m3() body

Changes req any one of below:
1. comment b.m3("prince"); in main() and call from m2();
2. pass instance of A to m3() ns et it there to a e.g
b.m3("prince", newA());

Just want to make sure my explaination is correct.
Do not meddle in the affairs of dragons - for you are crunchy and good with ketchup. Crunchy tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 625 times.
Similar Threads
why not NullPointerException
explain output
Two stupid questions about inheritance
Head First Java Mixed Message Chapter 7
Doubts in Assignments
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 15, 2024 22:26:47.