'getting nullpointerexception when trying to invoke method from another class even object was not null
I created three classes A,B and C in the class A declared class B and class C as references in the constructor A passed the B and C references by using the B's object reference invoked the function which is in class B it worked fine. But did the same thing with class B and invoked class C function getting runtime exception. Please Refer to the below code. Can anyone give clear explanation why the problem is occurring how to resolve it.
class A
{
B b;
C c;
A(B b,C c)
{
this.b=b;
this.c=c;
System.out.println("From Constructor Class A");
System.out.println(c);
}
void display()
{
b.displayB();
}
}
class B
{
C c;
B(C c)
{
this.c=c;
System.out.println("From Constructor C"+c);
}
B()
{
}
void displayB()
{
System.out.println(c);
System.out.println("From Class B");
c.displayC();
}
}
class C
{
C()
{
}
void displayC()
{
System.out.println("From Class C");
}
}
class Doubt
{
public static void main(String[] args)
{
B b1=new B();
C c1=new C();
System.out.println(c1);
A a=new A(b1,c1);
B b2=new B(c1);
a.display();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
