Reputation: 785
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?
Upvotes: 1
Views: 94
Reputation: 2833
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.
Upvotes: 2
Reputation: 726559
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.
Upvotes: 11