0

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.

Akhran
  • 13
  • 4

2 Answers2

1

If this is the exact code, which it can't be given the lack of the getClassA() method, you don't instantiate ClassB or Cso NPEs are expected.

ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75
0

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 ();
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64