Protected Access Flashcards

1
Q

Remind me of the definition of a protected method !

A

A protected method is a method that can only be accessed from within
the same package or by a subclass even if it is outside the package

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Write code to test all scenarios involving the protected access modifier !

A

All the possible ways a protected method may be attempted to gain access to are :
- from within the same class
- from a class within the same package
- from a class outside of the package

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Give me the scenarios under which the protected rules apply with giving examples that violate the scenarios ! (one of the most confusing points on the exam)

A

Accessing a protected member can be made under 2 scenarios :
- A member is used without referring to a variable, in this case, we are taking advantage of inheritance and protected access is allowed.

EXAMPLE :

package pond.swan;
import pond.shore.Bird; // in a different package
public class Swan extends Bird{

public void swim(){
5:floatInWater(); // package access to superclass
6:System.out.println(text); // package access to superclass
}

  • a member is used through a variable, in this case, the rules for the reference type are what matter : if a reference type is the same class or a subclass of the class that declares the protected member, access to that member is allowed if the access attempt is made from within the same package as the declaring class. Additionally, access is allowed to the protected member if the access attempt is made from outside the package, but only through an instance of the subclass and from the subclass itselfpackage pond.swan;
    import pond.shore.Bird; // in a different package
    public class Swan extends Bird{
    public void swim_2(){
    Swan swan=new Swan();
    10: swan.floatInWater(); // package access to superclass
    11: System.out.println(swan.text); // package access to superclass
    }

EXPLANATION :

Lines 10 and 11 also successfully use protected members of Bird.
This is allowed because these lines refer to a Swan object from with the Swan
class.
Swan inherits from Bird so this is okay.

package pond.swan;
import pond.shore.Bird; // in a different package
public class Swan extends Bird{
public void swan_3(){
14:Bird bird=new Bird();
15:bird.floatInWater(); // DOES NOT COMPILE 16:System.out.println(bird.text); // DOES NOT COMPILE
}

Bird is in a different package, and this code isn’t inheriting from Bird, so it doesn’t get to use protected members

How well did you know this?
1
Not at all
2
3
4
5
Perfectly