A Funny Java Flavoured Look at the World

Thursday, December 07, 2006

Constructor conundrum

I found an interesting constructor type conundrum this week.

I was created a class which held some values as instance parameters, a few strings and an Array. I then extended this class and hard coded some of the String values for the extended class. Basically I thought this was a decent way of placing the hard coded values into a little area, basically containing the hard coded values which could if later get the values from somewhere else (e.g. reading from a file).

The variables where initially private final Strings but then the constructor complained it couldn't see these values in a constructor. I got around the problem by making the values Static because I didn't actually want to change these values for each instance of the class.

The message was

"cannot refer to an instance field variable name whilst explicitly invoking a constructor"

It took my by surprise a bit and then I thought why is it coming out with this message, I thought that basically these variables should be created before the constructor had run. Then I did a bit more thinking and it occurred to me that the constructor has to have a super or call another constructor as the first line. This is because when Java creates a new instance of a class it has to run all constructors of the inherited classes first before it runs it's own constructor. Why does it do this because you might be using some of the values in the extendded class. As we know this means that Java has to run the constructor of Object class and set up its instance variables before it gets round to run the constructor of your class and initialising it's instance variables.

Anyway it was a slightly interesting (or not) not error but just the way Java works, it took me a little by surprise until I thought about it a bit.




If you like this blog or and fancy something a bit less technical with some laughing thrown in then check out my other blog Amusing IT Stories. Which is a blog about funny and amusing stories from the IT environment and the office. It is a mix of news, office humour, IT stories, links, cartoons and anything that I find funny

1 Comments:

  • Interesting problem it is, but quite annoying when you are trying to implement something quick and "simple". Nothing is simple in Java. That is why Python rules.
    :)

    By Anonymous Anonymous, at Mon Jun 30, 04:10:00 pm 2008  

Post a Comment

<< Home