This code compiles and runs fine. But if inside the go method while creating the instance of JButton if we mention it like JButton button = new JButton("click this") then it throws nullPointerException when we click on the button. I am not able to understand what is going wrong if reference type is also mentioned during the instance creation. Thank you in advance. This code will work
This code will throw nullPointerException.
[ November 23, 2008: Message edited by: david john ]
Joined: Nov 23, 2008
The reference to "button" in the "actionPerformed" method does not know the button that you declare locally in the "go" method. So, an Exception is thrown, because the instance variable "button" is not initialised.
Originally posted by david john: ... I am not able to understand what is going wrong if reference type is also mentioned during the instance creation...
To expand on what Andre said, when you specify the type before the variable name, you are declaring a new variable instead of using an existing variable. In this example, you have 2 different variables called "button." One is declared as an instance variable in the class guiAct, and the other is declared as a local variable within the scope of the method go. The "button" inside go is assigned to an instance, but the "button" in guiAct has a default value of null.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Oct 16, 2008
Marc, Andre... Thank you very much for the reply! Got the point.