Search code examples
javainheritancethissuper

Is it fine to use "this" meaning "super" to use a field


I have a class A which extends an abstract class B.

Let B have a protected field value

I wanna use this field in A. If A doesn't have value, I can write this.value to get it from B.

Is there any difference with super.value?


Solution

  • It depends ...

    If only class B declares a field value then it doesn't matter. But if class A would declare a field value too, then it would matter:

    Have a look at this example:

    public class A extends B {
    
      private Object value = "A";
    
      public void printValue() {
        System.out.println(super.value);
        System.out.println(this.value);
      }
    
      public static void main(String[] args) {
        A a = new A();
        a.printValue();
      }
    
    }
    

    If you run this code the output is:

    B
    A
    

    The JLS says

    The form super.Identifier refers to the field named Identifier of the current object, but with the current object viewed as an instance of the superclass of the current class

    Thus since the superclass B declares a the field value it is referred by super.value.

    Regarding the keyword this the JLS says:

    ... the keyword this denotes a value that is a reference to the object for which the instance method or default method was invoked ... The type of this is the class or interface type T within which the keyword this occurs.

    In your case the type of this is A. Thus this.value refers to the inherited field value declared in class B. But if class A would declare a field value, then this.value would refer to the field in class A.