It depends on how you are calling the class A. If the method calls in a constructor of class A, then it will be called each time a new instance is created and you may hit the limit on the number of SOQL queries in a transaction which would be 100
assuming this is the only code executing in the transaction.
In your case, the query will be called when you create an instance any try to access xyz
.
Class A
public with sharing class ClassA {
public Integer a = ClassB.method();
}
Class B
public with sharing class ClassB {
public static Integer method(){
return [SELECT count() FROM Contact];
}
}
Test Case 1: Query executed 1 time only.
ClassA a = new ClassA();
System.debug(a.a);
System.debug(a.a);
Test Case 1: Query executed 2 times.
ClassA a = new ClassA();
System.debug(a.a);
System.debug(a.a);
a = new ClassA();
System.debug(a.a);
System.debug(a.a);