protected
access
package model; public abstract class Shape ❶{ final protected long creationTime ❷= System.nanoTime(); ... } ------------------------------------------------ package model.sub; public class Rectangle ❸extends Shape { static final Logger log = LogManager.getLogger(Rectangle.class); @Override public double getArea() { log.info("Rectangle creation time:" + creationTime ❹); return width * height; } ... }
No. 175
protected
vs. “package
private”
Q: |
Implement Figure 494, “ Now apply the following two changes:
Are you still able to run your code? Explain the result. |
A: |
Implementing class
Executing 2018-01-03 08:31:18,811 INFO [main] sup.Circle (Circle.java:11) - Circle creation time:3340216708709 Removing public class Circle extends Shape {
static final Logger log = LogManager.getLogger(Circle.class);
@Override public double getArea() {
// Error: 'creationTime' is not public in 'testprotect.model.Shape'.
// Cannot be accessed from outside package
log.info("Circle creation time:" + creationTime );
... Moving class NoteIn a production environment this may or may not be desired and is thus a design choice. |
No. 176
protected
access involving different
instances
Q: |
We reconsider class package package_two; import package_one.Alpha; public class AlphaSub extends Alpha { void dummy(/* Inherited */) { int v; v = attribPublic; v = attribProtected; v = attribDefault; v = attribPrivate; } } If we try to access a different instance's package package_two;
import package_one.Alpha;
public class AlphaSub
extends Alpha {
void dummy(final Alpha a) {
int v;
...
v = a.attribProtected;
...
}
} Why is this access prohibited? Both the calling instance and
the argument |
A: |
The current use case differs: We have two (presumably
different) instances one trying to access another's |