function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
DaveHagmanDaveHagman 

Cant access private variables with methods in the same class???

So I have a class that contains a bunch of methods for performing actions on cases (sending emails, verification etc). Now I have a bunch of private final variable at the top that I want to create getters for but when I try to return the  value from a method in the same class I get this error: 

Save error: Variable does not exist: this.MBI_ID

 

Now the variable is declared private but I am accessing it within the same class. For some reason it does not see it. I have tried to return with and without the "this" keyword and it still does not work. I hope I am not just having a complete n00b moment here but any help would be appreciated. I posted a snippet below. Thanks in advance!

 

 

public with sharing class CaseUtils {
   final String MBI_ID = '0013000000XXXXXXXXX';
   
   public static String getMbiAcctId()
   { return MBI_ID; } // Tried with and without "this" keyword
}
   

 

 

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

Static functions can't access instance variables because they are, by definition, instanceless. In this case, your static function can't access this because there is no this for it to reference (this means an instance, and static members have no instance). You have two choices: 1) make MBI_ID static (instance functions can access it through CaseUtils.MBI_ID), or make getMBIAcctId() non-static (will require an instance to call the function).

 

Edit: Silly Typo, Trix Are For Kids!

All Answers

MandyKoolMandyKool

Hi,

 

Your getter method is "static" and in your static method you are using "this". 

 

Basic oops concepts, but yes we make mistakes!!!

 

DaveHagmanDaveHagman

I realize that and I like I said I tried with and without the "this" keyword and it did not work either way.

sfdcfoxsfdcfox

Static functions can't access instance variables because they are, by definition, instanceless. In this case, your static function can't access this because there is no this for it to reference (this means an instance, and static members have no instance). You have two choices: 1) make MBI_ID static (instance functions can access it through CaseUtils.MBI_ID), or make getMBIAcctId() non-static (will require an instance to call the function).

 

Edit: Silly Typo, Trix Are For Kids!

This was selected as the best answer
DaveHagmanDaveHagman

I completely forgot to make the variables static.... Thank you so much! That was kind of a n00b mistake but it happens.