Vilx-
Vilx-

Reputation: 106912

Are constructors optional in Java or what?

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?

Upvotes: 2

Views: 1302

Answers (5)

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

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).

Upvotes: 12

Mnementh
Mnementh

Reputation: 51311

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 = ....

Upvotes: 0

tangens
tangens

Reputation: 39733

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;

Upvotes: 0

Petar Minchev
Petar Minchev

Reputation: 47373

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

Upvotes: 0

pauljwilliams
pauljwilliams

Reputation: 19225

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.

Upvotes: 0

Related Questions