-1

I have following code

package com.kathy.accessmodifiers2;

public class base extends Object{
protected int a = 10;
}

package com.kathy.accessmodifiers;
import com.kathy.accessmodifiers2.*;

class derived extends base {
public void D() {
    System.out.println("D");
    base b = new base();
    System.out.println(super.a); //line 1
    //System.out.println(b.a); //line 2
    //Only this class can access the proctected member.
    System.out.println(this.a);
    System.out.println(a);
}
}

class derived2 extends derived {
public void D2() {
    System.out.println(a);
}
}

public class Protected {

public static void main(String str[]) {
    new derived2().D();
}
}

In line1, i am using super.a and the output is 10. In case of line2, the code does not compile because i am trying to access protected member of super class (different package) from base class (different package). Why in case of super the a is accessible ?

Not a bug
  • 4,286
  • 2
  • 40
  • 80
Naresh C
  • 63
  • 3
  • 9
  • Your `Derived` class has no visibility modifier and therefore uses package-private. If you declare it `public Derived extends Base`you should be fine. – Sambuca Nov 11 '13 at 11:30
  • @isnot2bad protected members are accessible by subclass which are inherited, not with instance of parent class. and `b` is instance of parent class here. – Not a bug Nov 11 '13 at 12:12
  • @KishanSarsechaGajjar You're right! I didn't notice the commented line 2. I just copied the source and compiled it. As javac did not complain, I assumed everything works. I'll remove my comment! – isnot2bad Nov 11 '13 at 13:36
  • @isnot2bad Its ok...you can refer my answer also...!! – Not a bug Nov 11 '13 at 16:50

2 Answers2

2

That is

protected member of a class of one package is accessible in another package if and only if this class is inherited by some other class in another package.

1 i.e in above example base class is extended by derived class in different package so its(base class) protected members are accessible by super keyword.

2 but we cannot directly access base class' protected members by creating its object in another package.because they are accessible in same package until we not inherit that class in another package

Not a bug
  • 4,286
  • 2
  • 40
  • 80
Tushar.k
  • 323
  • 4
  • 10
1
base b = new base();
System.out.println(super.a); //line 1
System.out.println(b.a); //line 2

In line 1 : super.myMethod() or super.variable will call a overridden method or to access overridden properties. so by line 1, you are accessing the overridden int a in child class.

while in line 2 : int a has protected access modifier in class B so you can not access it from different package, and you are trying to access the int a by b which is instance of class B from different package.

Simple is that.

Reference Javadoc :

  1. Using the Keyword super
  2. Controlling Access to Members of a Class
Not a bug
  • 4,286
  • 2
  • 40
  • 80