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
}
}
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
Bwhich shadows the one inA, then it makes a difference: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:
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.