Name Shadowing
A member variable can be shadowed by a local variable, especially a method parameter. The parameter can use the same name as the field. Use this to refer to the field, and the bare name to refer to the parameter.
1public with sharing class Shadow {
2 String s;
3
4 public Shadow(String s) {
5 this.s = s; // this.s is the field; s is the constructor argument
6 }
7
8 public void setS(String s) {
9 this.s = s; // this.s is the field; s is the method argument
10 }
11}A member variable in a subclass can shadow a member variable with the same name in a parent class. This can happen when the two classes are in different top-level classes and written by different teams. The compile-time type of the reference determines which field you get. To read the parent’s value, assign the object to a parent-class reference first.
Create this parent class.
1public virtual with sharing class FieldShadowParent {
2 public String label = 'parent';
3}Then create this subclass, which declares its own label.
1public with sharing class FieldShadowChild extends FieldShadowParent {
2 public String label = 'child';
3}This snippet shows the two fields. Run it after you create both classes.
1FieldShadowChild childRef = new FieldShadowChild();
2String fromChild = childRef.label; // child
3
4FieldShadowParent parentRef = childRef;
5String fromParent = parentRef.label; // parentStatic variables can also be shadowed across the class hierarchy. If a parent class defines a static variable, a subclass can declare a static variable with the same name. Inside the subclass, the bare name refers to the subclass static. Prefix the name with the parent class to get the parent’s value.
Create this parent class.
1public virtual with sharing class StaticShadowParent {
2 public static final String KIND = 'parent';
3}Then create this subclass.
1public with sharing class StaticShadowChild extends StaticShadowParent {
2 public static final String KIND = 'child';
3
4 public static String fromThisClass() {
5 return KIND; // child
6 }
7
8 public static String fromParentClass() {
9 return StaticShadowParent.KIND; // parent
10 }
11}Static variables cannot be referenced through a class instance. Use the variable name by itself (inside that class) or prefix it with the class name.
1String fromChild = StaticShadowChild.KIND; // child
2String fromParent = StaticShadowParent.KIND; // parent
3
4StaticShadowChild instance = new StaticShadowChild();
5// String fromInstance = instance.KIND; // Illegal. Use the class name, not an instance.