Friday, 23 August 2013

Can't use object variables without getter methods

Can't use object variables without getter methods

I have an abstract class, AbstractNode, and a concrete class which extends
it- Node.
I am trying to "program to an interface" by declaring objects of
AbstractClass and instantiating them with new Node().
When I try to use the variables in Node after initializing them in the
constructor, I get a Null Pointer. But everything works fine if I use a
getter method instead. What am I missing?
public abstract class AbstractNode
{
String str;
public abstract String getStr();
}
public class Node extends AbstractNode
{
String str;
public Node()
{
str= new String();
}
public String getStr()
{
return str;
}
}
And the main method looks like this:
public static void main(String[] args)
{
AbstractNode n= new Node();
String nullStr= n.str;
String regularStr= n.getStr();
}
Now, nullStr contains a null reference, and regularStr contains a
reference to n.str. What is happening in here? I can access other fields
which do not require initialization, like int, directly without any getter
methods.

No comments:

Post a Comment