This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Java in General and the fly likes String is not null, then it is? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "String is not null, then it is?" Watch "String is not null, then it is?" New topic
Author

String is not null, then it is?

colin shuker
Ranch Hand

Joined: Apr 11, 2005
Posts: 712
Hi,

I'm using 2 classes, Child and Parent.
In parent class, there is the abstract method setData() which is implemented in child class.
My problem is... setData() instantiates the String s, but when button is pressed, it says s is null.
However, if I invoke setData() in Child constructor whilst leaving Parent constructor empty,
then a button press says s is not null, which is what I want, but I really need it to work first way.
Code is below:





I don't understand why this is happening, can anyone help?
Thanks
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 3090
    
    5

Unfortunately you can't do that. See This recent CodeRanch thread on the same subject.

Basically, the body of the parent class's constructor gets called, which initializes the String. Only after the parent class is complete does the Child class's instance members get initialized, which in your case re-assigns the String s back to null.

You may consider making the String a protected member of the parent class if it needs to get built during the course Parent's constructor.


Steve
colin shuker
Ranch Hand

Joined: Apr 11, 2005
Posts: 712
Thanks very much, I never thougth of it like that..

I have managed to solve it by:


instead of

I always assumed it was irrelevent as null is the default value,
but now I can see it starts as null (default), then the constructor
is called, calling parent constructor, then it is set to null, if there
is an ' = null;'

I guess thats right
Thanks
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 3090
    
    5

colin shuker wrote:
I always assumed it was irrelevent as null is the default value,
but now I can see it starts as null (default), then the constructor
is called, calling parent constructor, then it is set to null, if there
is an ' = null;'


I had thought it wouldn't matter, as well... guess I was wrong. Good to know I guess.

I still believe that the data should be a member of the Parent class if it needs to be built when the parent constructor runs.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: String is not null, then it is?
 
Similar Threads
init blocks example
Constructor doubt
Gett8ing focus when 2 JTrees in same panel.
Question for variable initialization order
Constructor,why displaying null on this program