Java Reference
In-Depth Information
✓
✓
11.33
What modifier should you use on a class so that a class in the same package can
access it, but a class in a different package cannot access it?
Check
Point
11.34
What modifier should you use so that a class in a different package cannot access the
class, but its subclasses in any package can access it?
11.35
In the following code, the classes
A
and
B
are in the same package. If the question
marks in (a) are replaced by blanks, can class
B
be compiled? If the question marks
are replaced by
private
, can class
B
be compiled? If the question marks are
replaced by
protected
, can class
B
be compiled?
package
p1;
package
p1;
public class
A {
int
i;
public class
B
extends
A {
public void
m1(String[] args) {
System.out.println(i);
m();
?
?
void
m() {
...
}
}
}
}
(a)
(b)
11.36
In the following code, the classes
A
and
B
are in different packages. If the question
marks in (a) are replaced by blanks, can class
B
be compiled? If the question marks
are replaced by
private
, can class
B
be compiled? If the question marks are
replaced by
protected
, can class
B
be compiled?
package
p1;
package
p2;
public class
A {
int
i;
public class
B
extends
A {
public void
m1(String[] args) {
System.out.println(i);
m();
?
?
void
m() {
...
}
}
}
}
(a)
(b)
Neither a final class nor a final method can be extended. A final data field is a
constant.
Key
Point
You may occasionally want to prevent classes from being extended. In such cases, use the
final
modifier to indicate that a class is final and cannot be a parent class. The
Math
class is
a final class. The
String
,
StringBuilder
, and
StringBuffer
classes are also final
classes. For example, the following class
A
is final and cannot be extended:
public class
A {
// Data fields, constructors, and methods omitted
final
}