-5

I am way deep into Java which I am pretty much unaware off. But few days of reading has led me to this understanding - I cannot call a non-static method from a a method of a different class.

So, I have a non-static method inside a class (ClassA) with a constructor. Lets call this MethodA.

And in MethodB in ClassB, I am doing this,

MethodB{
public static CommandControl ab;
ClassA objectA = new ClassA(ab) 
objectA.MethodA(String S)
}

Now, I have a NullPointerException when the control goes inside ClassA since the value of ab = null.

How do I avoid this?

whydoieven
  • 589
  • 2
  • 7
  • 21
  • Make sure `ab` is not null of course. Give it a value before it is used. – Gimby Oct 22 '19 at 11:16
  • *"I cannot call a non-static method from a a method of a different class"* - This is a misleading statement. You *can* call a non-static method from anywhere, as long as you have an instance of such an object on which to call it. *"the value of ab = null"* - Because you never initialized it to anything. – David Oct 22 '19 at 11:16
  • 4
    you can't have a NullPointerException there, because that code will never compile. Could you please show an actual code sample where you reproduce the problem? – Stultuske Oct 22 '19 at 11:17

3 Answers3

0

Your understanding:

I cannot call a non-static method from a a method of a different class.

is wrong.

If you have created the object of the class containing the non-static method, you can call it.

You get a null pointer exception because the constructor of the ClassA does something with the CommandControl ab. And that ab is null in your case.

Ioannis Barakos
  • 1,319
  • 1
  • 11
  • 16
0

Unlike C/C++, Java requires you to explicitly create an instance using new keyword.

Your statement public static CommandControl ab; should be updated as public static CommandControl ab = new CommandControl();

0

Not fully clear , so I'll try to do some assumptions:

does class B is a child class of A? and does method B is called in the constractor of B? if so, then the variables are not instantiated yet since you are in the constractor.

eyalka
  • 21
  • 5