1.2 Develop code that declares an interface. Develop code
that implements or extends one or more interfaces. Develop
code that extends an abstract class.
1.4 Develop code that declares both static and non-static
methods, and - if appropriate - use method names that
adhere to the JavaBeans naming standards. Also develop
code that declares and uses a variable-length argument list.
5.3 Explain the effect of modifiers on inheritance with
respect to constructors, instance or static variables, and
instance or static methods.
7.1 Given a code example and a scenario, write code
that uses the appropriate access modifiers, package
declarations, and import statements to interact with
(through access or inheritance) the code in the example.
2. Modifier Overview
describe the attributes of a feature.
The most common modifiers are the access modifiers:
Public
Private
Protected
The remaining modifiers do not fall into any clear categorization. They are
Final
Abstract
Static
Native
Transient
Synchronized
volatile
In the following sections, we will first look at the access modifiers, and then look at the other
modifiers.
Ben Abdallah Helmi Architect
2
J2EE
3. The Access Modifiers
Access modifiers control which classes may use a feature.
A class’s features are
• The class itself
• Its member variables
• Its methods and constructors
• Its nested classes
Ben Abdallah Helmi Architect
3
J2EE
4. public
The most generous access modifier is public . A public
class, variable, or method may be used in any Java
program without restriction. Any public method may be
overridden by any subclass. An application declares its
main() method to be public so that main() can be invoked
from any Java runtime environment.
Ben Abdallah Helmi Architect
4
J2EE
5. private
The least generous access modifier is private . Top-level (that is, not inner) classes may not be declared
private. A Private variable or method may be used only by an instance of the class that declares the
variable or method. For an example of the private access modifier, consider the following code:
1. class Complex {
2. private double real, imaginary;
3.
4. public Complex(double r, double i) {
5. real = r; imaginary = i;
6. }
7. public Complex add(Complex c) {
8. return new Complex(real + c.real,
9. imaginary + c.imaginary);
10. }
11. }
12.
13. class Client {
14. void useThem() {
15. Complex c1 = new Complex(1, 2);
16. Complex c2 = new Complex(3, 4);
17. Complex c3 = c1.add(c2);
18. double d = c3.real; // Illegal!
19. }
20. }
Ben Abdallah Helmi Architect
5
J2EE
7. protected
It’s important to be aware that different-package subclasses don’t have unlimited access to protected superclass features.
In fact, different-package subclasses have only the following privileges:
•
They may override protected methods of the superclass.
•
An instance may read and write protected fields that it inherits from its superclass. However, the instance may not read
or write protected inherited fields of other instances.
•
An instance may call protected methods that it inherits from its superclass. However, the instance may not call
protected methods of other instances.
As an example of the protected access modifier, consider the following code:
1. package sportinggoods;
2. class Ski {
3. void applyWax() { . . . }
4. }
The applyWax() method has default access. Now consider the following subclass:
1. package sportinggoods;
2. class DownhillSki extends Ski {
3. void tuneup() {
4. applyWax();
5. // other tuneup functionality here 6. } 7. }
Ben Abdallah Helmi Architect
7
J2EE
9. 7. Given the following code, and making no other changes, which combination of access
modifiers
(public, protected, or private) can legally be placed before aMethod() on line 3 and be
placed before aMethod() on line 8?
1. class SuperDuper
2. {
3. void aMethod() { }
4. }
5.
6. class Sub extends SuperDuper
7. {
8. void aMethod() { }
9. }
A. line 3: public; line 8: private
B. line 3: protected; line 8: private
C. line 3: default; line 8: private
D. line 3: private; line 8: protected
Ben Abdallah Helmi Architect
9
E. line 3: public; line 8: protected
J2EE
10. 7. E. The basic principle is that a method may not be
overridden to be more private. All choices except E
make the access of the overriding method more private.
Ben Abdallah Helmi Architect
10
J2EE
11. 11. Suppose class Supe, in package packagea, has a
method called doSomething(). Suppose class
Subby, in package packageb, overrides doSomething().
What access modes may Subby’s
version of the method have? (Choose all that apply.)
A. public
B. protected
C. Default
D. private
Ben Abdallah Helmi Architect
11
J2EE
12. 11. A, B. Since the method in the superclass is
overridden in a different package, the superclass
version must be public or protected. (Default methods
may be overridden only if the subclass is in the same
package as the superclass; private methods may not be
overridden at all.) An overriding method’s access mode
must be the same as, or more open than, the superclass
version’s access mode.
Ben Abdallah Helmi Architect
12
J2EE
13. 16. Suppose class A has a method called
doSomething(), with default access. Suppose class B
extends A and overrides doSomething(). Which
access modes may apply to B’s version of
doSomething()? (Choose all that apply.)
A. public
B. private
C. protected
D. Default
Ben Abdallah Helmi Architect
13
J2EE
14. 16. A, C, D. An overriding method’s access mode must be
the same as, or more open than, the superclass version’s
access mode.
Ben Abdallah Helmi Architect
14
J2EE
15. 17. True or false: If class Y extends class X, the two
classes are in different packages, and class X has a
protected method called abby(), then any instance of
Y may call the abby() method of any other instance of
Y.
A. True
B. False
Ben Abdallah Helmi Architect
15
J2EE
16. 17. B. An object that inherits a protected method from a
superclass in a different package may call that method
on itself but not on other instances of the same class.
Ben Abdallah Helmi Architect
16
J2EE
17. final
The final modifier applies to classes, variables, and methods. The meaning of final varies from context to context, but the essential idea is
the same: final features may not be changed. A final class cannot be subclassed. For example, the following code will not compile,
because the java.lang.Math class is final:
class SubMath extends java.lang.Math { }
The compiler error says, “Can’t subclass final classes.”
A final variable cannot be modified once it has been assigned a value. In Java, final variables play the same role as consts in C++ and
#define constants in C. For example, the java.lang.Math class has a final variable, of type double, called PI. Obviously, pi is not the sort
of value that should be changed during the execution of a program. If a final variable is a reference to an object, it is the reference that
must stay the same, not the object. This is shown in the following code:
1. class Walrus {
2. int weight;
3. Walrus(int w) { weight = w; }
4. } 5.
6. class Tester {
7. final Walrus w1 = new Walrus(1500);
8. void test() {
9. w1 = new Walrus(1400); // Illegal
10. w1.weight = 1800; // Legal
11. } }
Ben Abdallah Helmi Architect
17
J2EE
18. You may not change a final object reference variable. You may change data owned by an object
that is referred to by a final object reference variable.
A final method may not be overridden. For example, the following code will not compile:
1. class Mammal {
2. final void getAround() { }
3. }
4.
5. class Dolphin extends Mammal {
6. void getAround() { }
7. }
Dolphins get around in a very different way from most mammals, so it makes sense to try to
override the inherited version of getAround(). However, getAround() is final, so the only result
is a compiler error at line 6 that says, “Final methods can’t be overridden.”
Ben Abdallah Helmi Architect
18
J2EE
19. 18. Which of the following statements are true?
A. A final class must be instantiated.
B. A final class must contain at least one final method.
C. A final class must contain at least one final data
field.
D. A final class may not be extended.
E. None of the above.
Ben Abdallah Helmi Architect
19
J2EE
20. 18. D. There is only one restriction on a final class: A
final class may not be extended.
Ben Abdallah Helmi Architect
20
J2EE
21. 19. Which of the following statements are true?
A. A final class must be instantiated.
B. A final class may only contain final methods.
C. A final class may not contain non-final data fields.
D. A final class may not be extended.
E. None of the above.
Ben Abdallah Helmi Architect
21
J2EE
22. 19. D. There is only one restriction on a final class: A
final class may not be extended.
Ben Abdallah Helmi Architect
22
J2EE
23. abstract
The abstract modifier can be applied to classes and
methods. A class that is abstract may not be instantiated
(that is, you may not call its constructor). Abstract classes
provide a way to defer implementation to subclasses.
Consider the class hierarchy shown in
Ben Abdallah Helmi Architect
23
J2EE
24. In fact, the compiler insists that a class must be declared
abstract if any of the following conditions is true:
• The class has one or more abstract methods.
• The class inherits one or more abstract methods (from an
abstract parent) for which it does not provide implementations.
• The class declares that it implements an interface but does
not provide implementations for every method of that
interface.
These three conditions are very similar to one another. In each
case, there is an incomplete class. Some part of the class’s
functionality is missing and must be provided by a subclass.
Ben Abdallah Helmi Architect
24
J2EE
25. 2. Which of the following statements is true?
A. An abstract class may not have any final methods.
B. A final class may not have any abstract methods.
Ben Abdallah Helmi Architect
25
J2EE
26. 2. B. Any class with abstract methods must itself be
abstract, and a class may not be both abstract and
final. Statement A says that an abstract class may not
have final methods, but there is nothing wrong with
this. The abstract class will eventually be subclassed,
and the subclass must avoid overriding the parent’s
final methods. Any other methods can be freely
overridden.
Ben Abdallah Helmi Architect
26
J2EE
27. 3. What is the minimal modification that will make this code compile correctly?
1. final class Aaa
2. {
3. int xxx;
4. void yyy() { xxx = 1; }
5. }6.7.
8. class Bbb extends Aaa
9. {
10. final Aaa finalref = new Aaa();
11.
12. final void yyy()
13. { 14. System.out.println("In method yyy()");
15. finalref.xxx = 12345;
16. }
17. }
A. On line 1, remove the final modifier.
B. On line 10, remove the final modifier.
C. Remove line 15.
D. On lines 1 and 10, remove the final modifier.
Ben Abdallah Helmi Architect
27
J2EE
28. 3. A. The code will not compile because on line 1, class
Aaa is declared final and may not be subclassed.
Lines 10 and 15 are fine. The instance variable finalref
is final, so it may not be modified; it can reference
only the object created on line 10. However, the data
within that object is not final, so nothing is wrong
with line 15.
Ben Abdallah Helmi Architect
28
J2EE
29. 12. Which of the following statements are true?
A. An abstract class may be instantiated.
B. An abstract class must contain at least one abstract
method.
C. An abstract class must contain at least one abstract
data field.
D. An abstract class must be overridden.
E. An abstract class must declare that it implements an
interface.
F. None of the above.
Ben Abdallah Helmi Architect
29
J2EE
30. 12. F. A is false because the compiler forbids
construction of an abstract class. B is false because
abstract classes need not contain any abstract methods
(though if a class does contain any abstract methods, it
must be abstract). C is false because there is no such
thing as an abstract data field. D is false because, when
you really think about it, it doesn’t make any sense; the
compiler compiles classes one at a time and has no
interest in whether or not a class is overridden. E is false
because there is no compiler requirement that an abstract
class must declare that it implements any interface.
Ben Abdallah Helmi Architect
30
J2EE
31. 13. Suppose interface Inty defines five methods.
Suppose class Classy declares that it implements Inty
but does not provide implementations for any of the
five interface methods. Which is/are true?
A. The class will not compile.
B. The class will compile if it is declared public.
C. The class will compile if it is declared abstract.
D. The class may not be instantiated.
Ben Abdallah Helmi Architect
31
J2EE
32. 13. C, D. If a class does not provide implementations for
all methods of all interfaces that the class declares it
implements, that class must be declared abstract.
Abstract classes may not be instantiated
Ben Abdallah Helmi Architect
32
J2EE
33. 14. Which of the following may be declared final?
(Choose all that apply.)
A. Classes
B. Data
C. Methods
Ben Abdallah Helmi Architect
33
J2EE
34. 14. A, B, C. Classes, data, and methods can be declared
final. Variables cannot.
Ben Abdallah Helmi Architect
34
J2EE
35. static
The static modifier can be applied to variables, methods,
and even a strange kind of code that is not part of a
method. You can think of static features as belonging to a
class, rather than being associated with an individual
instance of the class.
Ben Abdallah Helmi Architect
35
J2EE
36. • If a static method needs to access a nonstatic variable or call a nonstatic
method, it must specify which instance of its class owns the variable or
executes the method. This situation is familiar to anyone who has ever
written an application with a GUI:
1. import java.awt.*;
2.
3. public class MyFrame extends Frame {
4. MyFrame() {
5. setSize(300, 300);
6. }
7.
8. public static void main(String args[]) {
9. MyFrame theFrame = new MyFrame();
10. theFrame.setVisible(true);
11. }
Ben Abdallah Helmi Architect
12. }
36
J2EE
37. • A static method may access only the static data of its
class; it may not access nonstatic data.
• A static method may call only the static methods of its
class; it may not call nonstatic methods.
• A static method has no this.
• A static method may not be overridden to be nonstatic.
Ben Abdallah Helmi Architect
37
J2EE
38. Static Initializers
• It is legal for a class to contain static code that does not exist within a
method body. A class may have a block of initializer code that is simply
surrounded by curly braces and labeled static.
• For example:
1. public class StaticExample {
2. static double d = 1.23;
3.
4. static {
5. System.out.println("Static code: d=" + d++);
6. }
7.
8. public static void main(String args[]) {
9. System.out.println("main: d = " + d++);
Static code: d=1.23
10. }
main: d = 2.23
Ben Abdallah Helmi Architect
11. }
38
J2EE
39. Static Imports and Access
• You saw in Chapter 1, “Language Fundamentals,” that static
features of a class can be imported, using Java 1.5’s static import
facility. Static data and methods may have any of the four access
modes discussed earlier in this chapter: public, private, protected,
and default. A feature’s access mode dictates which source files
may statically import that feature.
When you think about how access mode affects static importing, you don’t have to consider class/subclass
relationships (which you have to do, for example, when thinking about protected features). This is because
static imports appear in source files just after package declarations, before any classes are defined.
Remember, you import into the namespace of a source file, not into the definition of a class. Architect
Ben Abdallah Helmi
39
J2EE
40. 5. Which statement is true about this application?
1. class StaticStuff
2{
3. static int x = 10;
4.
5. static { x += 5; }
6.
7. public static void main(String args[])
8. {
9. System.out.println("x = " + x);
10. }
11.
12. static {x /= 5; }
13. }
A. Lines 5 and 12 will not compile because the method names and return types are missing.
B. Line 12 will not compile because you can only have one static initializer.
C. The code compiles and execution produces the output x = 10.
D. The code compiles and execution produces the output x = 15.
E. The code compiles and execution produces the output x = 3.
Ben Abdallah Helmi Architect
40
J2EE
41. 5. E. Multiple static initializers (lines 5 and 12) are legal. All
static initializer code is executed at class-load time, so
before main() is ever run, the value of x is initialized to 10
(line 3), then bumped to 15 (line 5), and then divided by 5
(line 12).
Ben Abdallah Helmi Architect
41
J2EE
42. 6. Which statement is true about this code?
1. class HasStatic
2. {
3. private static int x = 100;
4.
5. public static void main(String args[])
6. {
7. HasStatic hs1 = new HasStatic();
8. hs1.x++;
9. HasStatic hs2 = new HasStatic();
10. hs2.x++;
11. hs1 = new HasStatic();
12. hs1.x++;
13. HasStatic.x++;
14. System.out.println("x = " + x);
15. }
16. }
A. Line 8 will not compile because it is a static reference to a private variable.
B. Line 13 will not compile because it is a static reference to a private variable.
C. The program compiles and the output is x = 102.
D. The program compiles and the output is x = 103.
E. The program compiles and the output is x = 104.
Ben Abdallah Helmi Architect
42
J2EE
43. 6. E. The program compiles fine; the “static reference to
a private variable” stuff in answers A and B is
nonsense. The static variable x gets incremented
four times, on lines 8, 10, 12, and 13.
Ben Abdallah Helmi Architect
43
J2EE
44. 9. This question concerns the following class definition:
1. package abcde;
2.
3. public class Bird {
4. protected static int referenceCount = 0;
5. public Bird() { referenceCount++; }
6. protected void fly() { /* Flap wings, etc. */ }
7. static int getRefCount() { return referenceCount; }
8. }
Which statement is true about class Bird and the following class Parrot?
1. package abcde;
2.
3. class Parrot extends abcde.Bird {
4. public void fly() {
5. /* Parrot-specific flight code. */
6. }
7. public int getRefCount() {
8. return referenceCount;
9. } 10. }
A. Compilation of Parrot.java fails at line 4 because method fly() is protected in the superclass, and classes Bird and
Parrot are in the same package.
B. Compilation of Parrot.java fails at line 4 because method fly() is protected in the superclass and public in the subclass,
and methods may not be overridden to be more public.
C. Compilation of Parrot.java fails at line 7 because method getRefCount() is static in the superclass, and static methods
Ben Abdallah Helmi Architect
may not be overridden to be nonstatic.
J2EE
44
45. 9. C. Static methods may not be overridden to be
nonstatic. B is incorrect because it states the case
backward: methods can be overridden to be more
public, not more private. Answers A, D, and E make
no sense.
Ben Abdallah Helmi Architect
45
J2EE
46. 10. This question concerns the following class definition:
1. package abcde;
2.
3. public class Bird {
4. protected static int referenceCount = 0;
5. public Bird() { referenceCount++; }
6. protected void fly() { /* Flap wings, etc. */ }
7. static int getRefCount() { return referenceCount; }
8. }
Which statement is true about class Bird and the following class Nightingale?
1. package singers;
2.
3. class Nightingale extends abcde.Bird {
4. Nightingale() { referenceCount++; } 5.
6. public static void main(String args[]) {
7. System.out.print("Before: " + referenceCount);
8. Nightingale florence = new Nightingale();
9. System.out.println(" After: " + referenceCount);
10. florence.fly(); 11. }12. }
A. The program will compile and execute. The output will be Before: 0 After: 2.
B. The program will compile and execute. The output will be Before: 0 After: 1.
C. Compilation of Nightingale will fail at line 4 because static members cannot be overridden.
Ben Abdallah Helmi Architect
D. Compilation of Nightingale will fail at line 10 because method fly() is protected in the
46
J2EE
47. 10. A. There is nothing wrong with Nightingale. The static
referenceCount is bumped twice: once on line 4 of
Nightingale and once on line 5 of Bird. (The no-argument
constructor of the superclass is always implicitly called at
the beginning of a class’s constructor, unless a different
superclass constructor is requested. This has nothing to
do with modifiers; see Chapter 6.) Because
referenceCount is bumped twice and not just once,
answer B is wrong. C says that statics cannot be
overridden, but no static method is being overridden on
line 4; all that is happening is an increment of an inherited
static variable. D is wrong because protected is precisely
the access modifier you want Bird.fly() to have: you are
calling Bird.fly() from a subclass in a different package.
Answer E is ridiculous, but it uses credible terminology.
Ben Abdallah Helmi Architect
47
J2EE
48. 15. Which of the following may follow the static
keyword? (Choose all that apply.)
A. Class definitions
B. Data
C. Methods
D. Code blocks enclosed in curly brackets
Ben Abdallah Helmi Architect
48
J2EE
49. 15. B, C, D. Classes may not be static. Data and
methods may be static, and often they are. When the
static keyword is followed by a code block, the block is a
static initializer and is executed when the class is loaded
Ben Abdallah Helmi Architect
49
J2EE
50. 20. What does the following code print?
public class A
{
static int x;
public static void main(String[] args) {
A that1 = new A();
A that2 = new A();
that1.x = 5;
that2.x = 1000;
x = -1;
System.out.println(x);
}
}
A. 0
B. 5
C. 1000
D. -1
Ben Abdallah Helmi Architect
50
J2EE
51. 20. D. Since x is static, there is only one variable, which
is shared by all instances along with the class. Thus
the last assignment wins.
Ben Abdallah Helmi Architect
51
J2EE
52. native
The native modifier can refer only to methods. Like the abstract modifier, native indicates
that the body of a method is to be found elsewhere. In the case of abstract methods, thebody
is in a subclass; with native methods, the body lies entirely outside the Java Virtual Machine
(JVM), in a library.
Native code is written in a non-Java language, typically C or C++, and compiled for a single
target machine type. (Thus Java’s platform independence is violated.) People who port Java
to new platforms implement extensive native code to support GUI components, network
communication, and a broad range of other platform-specific functionality. However, it is rare
for application and applet rogrammers to need to write native code.
One technique, however, is of interest in light of the last section’s discussion of static code.
When a native method is invoked, the library that contains the native code ought to be loaded
and available to the JVM; if it is not loaded, there will be a delay. The library is loaded by
calling System.loadLibrary (“library_name”) and, to avoid a delay, it is desirable to make this
call as early as possible. Often programmers will use the technique shown in the following
code sample, which assumes the library name is MyNativeLib:
Ben Abdallah Helmi Architect
52
J2EE
53. 1. class NativeExample {
2. native void doSomethingLocal(int i);
3.
4. static {
5. System.loadLibrary("MyNativeLib");
6. }
7. } Callers of native methods do not have to know that the
method is native. The call is made in exactly the same
way as if it were nonnative:
1. NativeExample natex;
2. natex = new NativeExample();
3. natex.doSomethingLocal(5);
Many common methods are native, including the clone()
and notify() methods of the Object class.
Ben Abdallah Helmi Architect
J2EE
53
54. transient
The transient modifier applies only to variables. A transient variable is not stored as part of its object’s persistent state
Many objects (specifically, those that implement the Serializable or Externalizable interfaces) can have their state serialized and written
to some destination outside the JVM. This is done by passing the object to the writeObject() method of the ObjectOutputStream
class. If the stream is chained to a FileOutputStream, then the object’s state is written to a file. If the stream is chained to a socket’s
OutputStream, then the object’s state is written to the network. In both cases, the object can be reconstituted by reading it from an
ObjectInputStream. Sometimes an object contains extremely sensitive information. Consider the following class:
1. class WealthyCustomer
2. extends Customer implements Serializable {
3. private float $wealth;
4. private String accessCode; 5. }
Once an object is written to a destination outside the JVM, none of Java’s elaborate security mechanisms is in effect. If an instance of
this class were to be written to a file or to the Internet, somebody could snoop the access code. Line 4 should be marked with the
transient keyword:
1. class WealthyCustomer
2. extends Customer implements Serializable {
3. private float $wealth;
4. private transient String accessCode;
5. }
Now the value of accessCode will not be written out during serialization.
Ben Abdallah Helmi Architect
54
J2EE
55. 4. Which of the following statements is true?
A. Transient methods may not be overridden.
B. Transient methods must be overridden.
C. Transient classes may not be serialized.
D. Transient variables must be static.
E. Transient variables are not serialized.
Ben Abdallah Helmi Architect
55
J2EE
56. 4. E. A, B, and C don’t mean anything because only
variables may be transient, not methods or classes. D
is false because transient variables need not be
static, and in fact they very rarely are.. E is a good
one-sentence definition of transient.
Ben Abdallah Helmi Architect
56
J2EE
57. 8. Which modifier or modifiers should be used to
denote a variable that should not be written out as
part of its class’s persistent state? (Choose the
shortest possible answer.)
A. private
B. protected
C. private protected
D. transient
E. volatile
Ben Abdallah Helmi Architect
57
J2EE
58. 8. D. A and B are access modifiers. C is an illegal
combination of two access modifiers. E (“volatile”)is
used for certain multi-threaded situations, and is not
covered in the Exam.
Ben Abdallah Helmi Architect
58
J2EE
59. volatile
The volatile modifier is not in common use. Only variables
may be volatile; declaring them so indicates that such
variables might be modified asynchronously, so the
compiler takes special precautions. Volatile variables are
of interest in multiprocessor environments.
Ben Abdallah Helmi Architect
59
J2EE
60. synchronized
• The synchronized modifier is used to control access to
critical code in multithreaded programs.Multithreading is
an extensive topic in its own right and is covered in
Chapter 7.
Ben Abdallah Helmi Architect
60
J2EE
61. Modifiers and Features
Note that classes here are strictly top-level (that is, not inner) classes.
Ben Abdallah Helmi Architect
61
J2EE
62. 1. Which of the following declarations are illegal?
(Choose all that apply.)
A. default String s;
B. transient int i = 41;
C. public final static native int w();
D. abstract double d;
E. abstract final double hyperbolicCosine();
Ben Abdallah Helmi Architect
62
J2EE
63. 1. A, D, E. A is illegal because “default” is not a
keyword. B is a legal transient declaration. C is
strange but legal. D is illegal because only methods
and classes may be abstract. E is illegal because
abstract and final are contradictory.
Ben Abdallah Helmi Architect
63
J2EE