It�s easy. Your exception is thrown because you have declared a classC reference variable which doesn�t point to any object of type ClassC. So, you are calling a method which can�t be accessed, remember you doesn�t have an object that can call the method, you only have a reference variable, but to do this
public ClassC classC;
doesn�t create an object.
Look at ClassA, you are instantiating an object in ClassB classB=new ClassB();, try to do the same in ClassB, write ClassC classC=new ClassC();, it must compile and run fine.
Joined: Nov 22, 2007
Thanks Alejandro.. So bad of me!! didnt get that thing
Originally posted by Maya Raj: Thanks Alejandro.. So bad of me!! didnt get that thing
anyways thanks a lot for clearing my doubt
Alejandro Galv�n 's explanation is perfect.
Fine, if you want to access an instance method what you need is an instance.
When you get an instance is actually when you create an instance. How do you create an instance? Obviously by invoking through new, like
The above step creates a brand new object (instance) of <className> and assigns it to the <referenceVarName>.
In your Class B, what you have is just a reference variable
To make that work, you need to create an instance/object and assign the object to this reference variable as what you have correctly done in you class A's getValue() method.
Just cross check the same and compare. You will get it!
Since you do NOT have any real object existing and you are trying to so-called-imaginary-object through a reference variable classC in the getValue() method of ClassB, the runtime environment does have any real object to drill down. According to it, the classC reference variable is NULL. Means, it points to nowhere. So it gives you a traditional, famous NullPointerException.