• Post Reply Bookmark Topic Watch Topic
  • New Topic

String is not null, then it is?  RSS feed

 
colin shuker
Ranch Hand
Posts: 750
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
colin shuker
Ranch Hand
Posts: 750
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!