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. 167
protected
vs. “package
private”
Q: |
Implement Figure 493, “ Now apply the following two changes:
Are you still able to run your code? Explain the result. |
A: |
Implementing class public class Circle extends Shape { static final Logger log = LogManager.getLogger(Circle.class); @Override public double getArea() { log.info("Circle creation time:" + creationTime ); return Math.PI * radius * radius; } private double radius; } 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. 168
protected
access involving different
instances
Q: |
We reconsider class
If we try to access a different instance's
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 |