Skip to content
Advertisement

Exception while trying to invoke method, which invokes method from other class through object of said class

In a program I made, I have a class canteen and a meal of the day class. In my meal of the day class there are several methods which I wanna use in my other class, implementing them in that classes’ methods without any kind of inheritence.

Therefore, I create objects of the meal of the day class so I can then use said methods from the canteen class. However, whenever I try to call those methods in my main method I always get the same exception no matter what method I use saying “Cannot invoke “cantina.PratoDia.METHODxyz()” because “this.p1″ is null”, despite the fact that I have a constructor attributing values to p1, p2 and p3. Not sure what is wrong here so help’s appreciated.

Leaving both the classes below with constructors and a method from each that are supposed to interact with each other and also the main method.

JavaScript
JavaScript

Advertisement

Answer

You defined the variables named p1, p2, and p3 in your global scope. Inside your Cantina constructor, you create new variables, again with the names p1, p2 and p3. By writing the type of the variable before the name, you create a new variable with the same name, overwriting the variable in the parent scope. Because of this, your global p1 is never actually assigned, and has a value of null. Simply remove the type indicators in the constructor, and it should work.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement