Reputation: 106912
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
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
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
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
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
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