Exercise: Declarations And Access Control

Questions for: Declarations And Access Control

Which is a valid declaration within an interface?
A:
public static short stop = 23;
B:
protected short stop = 23;
C:
transient short stop = 23;
D:
final void madness(short stop);
Answer: A

(A) is valid interface declarations.

(B) and (C) are incorrect because interface variables cannot be either protected or transient. (D) is incorrect because interface methods cannot be final or static.

Given a method in a protected class, what access modifier do you use to restrict access to that method to only the other members of the same class?
A:
final
B:
static
C:
private
D:
protected
Answer: C

The private access modifier limits access to members of the same class.

Option A, B, D, and E are wrong because protected are the wrong access modifiers, and final, static, and volatile are modifiers but not access modifiers.

Which two cause a compiler error?
  1. float[ ] f = new float(3);
  2. float f2[ ] = new float[ ];
  3. float[ ]f1 = new float[3];
  4. float f3[ ] = new float[3];
  5. float f5[ ] = {1.0f, 2.0f, 2.0f};
A:
2, 4
B:
3, 5
C:
4, 5
D:
1, 2
Answer: D

(1) causes two compiler errors ( '[' expected and illegal start of expression) because the wrong type of bracket is used, ( ) instead of [ ]. The following is the correct syntax: float[ ] f = new float[3];

(2) causes a compiler error ( '{' expected ) because the array constructor does not specify the number of elements in the array. The following is the correct syntax: float f2[ ] = new float[3];

(3), (4), and (5) compile without error.

Which of the following class level (nonlocal) variable declarations will not compile?
A:
protected int a;
B:
transient int b = 3;
C:
private synchronized int e;
D:
volatile int d;
Answer: C

Option C will not compile; the synchronized modifier applies only to methods.

Option A and B will compile because protected and transient are legal variable modifiers. Option D will compile because volatile is a proper variable modifier.

Which two of the following are legal declarations for nonnested classes and interfaces?
  1. final abstract class Test {}
  2. public static interface Test {}
  3. final public class Test {}
  4. protected abstract class Test {}
  5. protected interface Test {}
  6. abstract public class Test {}
A:
1 and 4
B:
2 and 5
C:
3 and 6
D:
4 and 6
Answer: C

(3), (6). Both are legal class declarations.

(1) is wrong because a class cannot be abstract and finalÒ€”there would be no way to use such a class. (2) is wrong because interfaces and classes cannot be marked as static. (4) and (5) are wrong because classes and interfaces cannot be marked as protected.

Ad Slot (Above Pagination)
Quiz