6.6.2. Details on protected Access
A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.
18.104.22.168. Access to a protected Member
Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.
In addition, if Id denotes an instance field or instance method, then:
If the access is by a qualified name Q.Id or a method reference expression Q :: Id (§15.13), where Q is an ExpressionName, then the access is permitted if and only if the type of the expression Q is S or a subclass of S. If the access is by a field access expression E.Id, or a method invocation expression E.Id(...), or a method reference expression E :: Id, where E is a Primary expression (§15.8), then the access is permitted if and only if the type of E is S or a subclass of S. If the access is by a method reference expression T :: Id, where T is a ReferenceType, then the access is permitted if and only if the type T is S or a subclass of S.
Claudiu Stroe wrote:After practicing and done some experiments I got it!
In the beginning I missunderstood the concept of protected.
Claudiu Stroe wrote:Thanks Roel for this challenge!
Claudiu Stroe wrote:For line 1 - Tadpole's ribbit() method is protected so it si not accesibile here. It is accesible only in the subclass , or in the same package, but main method is now in SuperClass
Claudiu Stroe wrote:for line 2 - Tadpole's ribbit() method must be used here, but since is not accesilbe here we have again a compile error
Claudiu Stroe wrote:bt.ribbit(); // BigTadpole's ribbit() method is not accesible here
Claudiu Stroe wrote:t.ribbit(); // it compiles here and outputs "Tadpole ribbit"
Claudiu Stroe wrote:f.ribbit(); // it compliles to, Tadpole's ribbit() method is outputed here,
Claudiu Stroe wrote:Here if we use
Tadpole bt = BigTadpole();
BigTadpole bt = new BigTadpole();
bt.ribbit(); will compile and the output would be "BigTadpole ribbit".
Claudiu Stroe wrote:1. If the main method is in the reference class, the compiler knows that all methods in that class are available.( All access modifiers are available in the same class)
Claudiu Stroe wrote:2. If the reference class's available methods are override in the object class,the overidden version will be outputed at runtime. (Only the reference class's variables are available)
Claudiu Stroe wrote:3. If the reference class is different from the class that has the main method, you can access those methods only if the access modifier permit it :
- private is never accessed here;
- package-private is availble if the class that has the main method is in the same package;
- protected - is tha same as default modifer + gives access to subclasses ( only if the reference is the class that has the main() and equals to a subclass) ;
- public - accesible anywhere;