Java Reference
In-Depth Information
Note
A subclass may override a protected method defined in its superclass and change its
visibility to public. However, a subclass cannot weaken the accessibility of a method
defined in the superclass. For example, if a method is defined as public in the superclass,
it must be defined as public in the subclass.
change visibility
✓
✓
11.37
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.38
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.39
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 {
?
public class
B
extends
A {
public void
m1(String[] args) {
System.out.println(i);
m();
}
}
int
i;
?
void
m() {
...
}
}
(a)
(b)
11.40
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 {
?
public class
B
extends
A {
public void
m1(String[] args) {
System.out.println(i);
m();
}
}
int
i;
?
void
m() {
...
}
}
(a)
(b)
Neither a final class nor a final method can be extended. A final data field is a
constant.
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:
Key
Point
public final class
A {
// Data fields, constructors, and methods omitted
}
Search WWH ::
Custom Search