1
class SomeClass1 {
  void method1() { }
  public void method2() { }
  private void method3() { }
  protected void method4() { }
}
class DemoClass{
  public static void main(String[] parameters) {
    SomeClass1 sc = new SomeClass1();
    sc.method1();
    sc.method2();
    sc.method4();
  }
}

Protected methods can only be accessed by classes that inherits the super class. As we can see here DemoClass does not extend SomeClass. But yet, it is able to access the protected method. How is this possible?

lichengwu
  • 4,277
  • 6
  • 29
  • 42
Tarun Mohandas
  • 765
  • 1
  • 8
  • 15

2 Answers2

11

That's because they are in the same package:

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

(Link to the documentation).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thank you that was very helpful. The definition really helped me a lot – Tarun Mohandas Feb 18 '13 at 15:47
  • @TarunMohandas You are welcome! If you find an answer helpful, consider accepting it by clicking the grey check mark next to it. This would tell others that you are no longer actively looking for an improved answer, and earn you a brand-new badge on Stack Overflow. – Sergey Kalinichenko Feb 18 '13 at 15:48
2

See In Java, difference between default, public, protected, and private

Basically, protected can be accessed from class, subclass and package. The two classes are in the same package, hence no error.

Community
  • 1
  • 1
kufudo
  • 2,803
  • 17
  • 19