I have this Apex class where I have custom objects as defined and debug statements. From the code it seems it is not able to build subObject here.

global class TestApexClass {
   global static void buildObject(string fname, string lname) {
      Ethnicity e = new Ethnicity('North America', 'Mixed');
      System.debug('location: ' + e.location);
      MyPersonObject obj = new MyPersonObject(fname, lname, e);
      System.debug('personObject: ' + obj);
   public class MyPersonObject {
      public String firstName;
      public String lastName;
      public Ethnicity e;
      public MyPersonObject(String fname, String lname, Ethnicity e) {
         firstName = fname; lastName = lname; e = e;
   public class Ethnicity {
      public String location;
      public String race;
      public Ethnicity(String l, String r) {
         location = l; race = r;

Here is my debug output: location: North America personObject: MyPersonObject:[e=null, firstName=John, lastName=Doe]

Is there a reason why "e" returns a null value?

1 Answer 1


This is because of "name shadowing." You named both the parameter e and the property e, so you're just assigning the value to itself (i.e. nothing happens). You need to use this if you shadow a variable and need access to the class variable instead:

     firstName = fname; lastName = lname; this.e = e;

I always recommend avoiding using the same name between class properties and function parameter names, because this tends to cause unintentional bugs.

  public MyPersonObject(String fname, String lname, Ethnicity eth) {
     firstName = fname; lastName = lname; e = eth;

The alternative is to always use this to refer to class variables, but that's almost always inefficient in terms of time it takes to write code and CPU execution time.

As a final note, avoid using one-letter variable names. These are non-descriptive, and tends to lead to code being more difficult to understand in exchange for saving a few characters; longer variable names are self-documenting. The exception to this rule are names like i or x for loop indices.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .