Search code examples
javanullpointerexceptioncomposition

Composition: How to access non-static variables with dot notation without nullpointerexception?


Very often, I see non-static variable in 'nested' classes (not exactly inner class kind of nested but class composition) being accessed via the dot notation.

Eg.

int a = getClassA().classB.classC.x; where 

getClassA() return an object of type Class A and x is the variable we are interested to access.

classB is a variable in ClassA.

classC is a variable in ClassB.

x is a variable in ClassC.

However, when I tried to recreate a similar test scenario, I get NullPointerException error.

Code

public class Main() 
{
public static void main(String[] args) {

int a = getClassA().classB.classC.x;
}
}

public class ClassA 
{
ClassB classB;
}


public class ClassB 
{
ClassC classC;
}


public class ClassC 
{
int x = 1;
}

//Class Main, A, B and C are in separate files.

Add-on

Read somewhere that in c# there is auto implemented property. For the example above, Class A will be

public Class A {
private ClassB _classB;

public ClassB classB
{
get {
    if (_classB == null) _classB = new ClassB();
    return _classB; }
set {_classB = value; }
}
}

So, ClassB is instantiated as it is accessed via the dot notation. Is there something similar in Java?

Appreciate any help on this.

Thank you.


Solution

  • ensure that Objects are not null by instantiating them

    e.g.

    public class ClassA 
    {
        ClassB classB = new ClassB ();
    }
    
    public class ClassB 
    {
        ClassC classC = new ClassC ();
    }