1

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{ 
    public void printA()
{
    System.out.print(super.a) // prints 15
    System.out.print(this.a) // prints 15
 }   

}

Phoenix
  • 8,357
  • 16
  • 51
  • 84

1 Answers1

4

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,335,956
  • 823
  • 8,931
  • 9,049
  • 1
    Ideed, member variables are not overridable. : [see this other thread](http://stackoverflow.com/q/685300/233495) – baraber Aug 07 '12 at 20:38