2

In terms of values for properties defined in the super class using the same property in the sub-class and the property is defined as protected, then using super or this does not make any difference right? Then why does the language really have these ways of accessing the properties? Is there a scenario where they will have different values?

class A {
    protected int a = 15; 
}
        
class B extends A { 
    public void printA() {
        System.out.print(super.a) // prints 15
        System.out.print(this.a) // prints 15
    }
}
Minding
  • 1,383
  • 1
  • 17
  • 29
Phoenix
  • 8,695
  • 16
  • 55
  • 88

1 Answers1

5

In this situation, it doesn't make any difference. However, as soon as you change to methods instead of variables, and introduce another method in B which shadows the one in A, then it makes a difference:

class A { 
    protected int a = 15; 
}

class B extends A { 
    private int a = 10;

    public void printA() {
       System.out.println(super.a); // prints 15
       System.out.println(this.a); // prints 10
    }
}

This is more common with methods than with fields though - often an overriding implementation needs to call the superclass implementation as part of its implementation:

public void foo() {
    super.foo();
    // Now do something else
}

I would personally recommend avoiding non-private fields, at which point the field part becomes irrelevant.

See section 6.4.1 of the JLS for more on shadowing.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Ideed, member variables are not overridable. : [see this other thread](http://stackoverflow.com/q/685300/233495) – baraber Aug 07 '12 at 20:38