views:

128

answers:

5

I'm a C# programmer trying to hack at a Java project. Here's an anonymized extract from our production code. It works (I think). Note that this is the whole class.

public class Y extends X
{
  public Z m_Z;

  protected void readCustomData (CustomStream reader, boolean forUpdate)
    throws IOException, FTGException
  {
    super.readCustomData (reader, forUpdate) ;
    m_Z.readBinaryData (reader, forUpdate) ;
  }

  protected void writeCustomData (CustomStream writer, int original)
    throws IOException, FTGException
  {
    super.writeCustomData (writer, original) ;
    m_Z.writeBinaryData (writer, original) ;
  }
}

What puzzles me is - where is m_Z initialized? I cannot find it in the entire codebase. So why don't the readCustomData and writeCustomData methods fail with NullReferenceException - or whatever the equivalent is in Java? Is m_Z somehow automagically constructed along with Y? Or have I missed something after all and there is some deeper magic in the codebase which initializes it?

+10  A: 

When a Java class does not declare a constructor, the compiler implicitly adds a no-argument constructor that does nothing but call the superclass no-argument constructor (if there is none such, there will be a compiler error).

However, in your example the field m_Z would be null. If calls to those method succeed, then the field must be set elsewhere. It is public, after all (very bad practice).

Michael Borgwardt
Beat me to it, and great point about the public field. Talk about a code smell.
I82Much
Code smell no doubt, but that's besides the point. Let's just say that's the least of code smells in that project. :) Anyways, thanks for the clarification. I'll continue my hunt then.
Vilx-
I don't remember the last time I used a public variable. Maybe never.
Tony Ennis
A: 

m_Z is public, so it can be initialised outside the class:

Y y = new Y();
y.m_Z = new Z();
y.readCustomData(...);

Would work OK.

Horrible code though.

Visage
A: 

m_Z variable is public. Is there a chance that someone from outside sets it? Although this is a pretty bad practice...

Petar Minchev
+1  A: 

If you have no constructor, java creates a default constructor for you. All members are initialized with the given value or, if no value is given, with null. That means, if your member m_Z is set, it was set from somewhere else (it's a public member), because the default constructor has initialized m_Z with null;

tangens
A: 

In the code given m_Z is never initialized, so it is null. But it can be accessed from outrside (public), so the value can be set by y.m_Z = ....

Mnementh