Java Chapter 7 Part 1 Flashcards

(399 cards)

1
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the implicit modifier for the getSpeed() method in the CanBurrow interface, and how would you explicitly write it?

A

The implicit modifier is public abstract. Explicitly: public abstract Float getSpeed(int age);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What modifier is implicitly applied to the MINIMUM_DEPTH variable in the CanBurrow interface, and why can’t it be changed after declaration?

A

public static final. It can’t be changed because final makes it a constant.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What Java version introduced default methods in interfaces, and what is the output of this code:

A

Java 8. Output: “Burrowing animal”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Identify the error in this interface implementation:

A

The method visibility is reduced (missing public). Interface abstract methods must be implemented as public.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the purpose of the private log() method in the CanBurrow interface, and which Java version enabled this feature?

A

It’s a helper method for internal interface use (e.g., logging). Added in Java 9.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How would you call the static isFast() method from the CanBurrow interface, and what does isFast(3) return?

A

Call via CanBurrow.isFast(3). Returns false (3 ≤ 5).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Which of these interface declarations is invalid and why?

A

Option A is invalid because interfaces cannot have instance variables (only public static final constants).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What happens if a class implements two interfaces with conflicting default methods, and how can this be resolved?

A

Compilation error occurs. Resolution: The class must override the conflicting method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

True or False: An interface can extend multiple interfaces, and a class can implement multiple interfaces. Provide a code example of multi-interface implementation.

A

True. Example: java class Frog implements CanBurrow, Climb, Swim { public Float getSpeed(int age) { return 1.5f; } // Other abstract methods from Climb/Swim must also be implemented }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the purpose of the @Override annotation in Java? Provide a code example.

A

The @Override annotation indicates that a method is intended to override a method in a superclass or interface. Example: java @Override public String toString() { return “Overridden toString()”; }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What does the @Deprecated annotation do? Include a code snippet showing its usage with additional parameters.

A

The @Deprecated annotation marks a class, method, or field as obsolete. Example with parameters: java @Deprecated(since=”9”, forRemoval=true) public class LegacySystem { // … }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How does @SuppressWarnings work? Provide an example where it suppresses raw type warnings.

A

@SuppressWarnings tells the compiler to ignore specific warnings. Example suppressing raw types: java @SuppressWarnings(“rawtypes”) public class Box { private List contents; }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the purpose of @SafeVarargs, and when should it be used? Include a code example.

A

@SafeVarargs asserts that a varargs method performs no unsafe operations on its parameters. Example: java @SafeVarargs public final <T> List<T> asList(T... a) { return Arrays.asList(a); }</T></T>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does the @FunctionalInterface annotation indicate? Provide a valid usage example.

A

@FunctionalInterface marks an interface as having exactly one abstract method (for lambda compatibility). Example: java @FunctionalInterface interface Runner { void run(); }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Identify the correct syntax for suppressing unchecked warnings in a Java class.

A

Use @SuppressWarnings(“unchecked”) above the class, method, or field. Example: java @SuppressWarnings(“unchecked”) List<String> list = new ArrayList();</String>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Can an interface be instantiated in Java?

A

No, interfaces cannot be instantiated directly in Java.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Can an abstract class be instantiated in Java?

A

No, abstract classes cannot be instantiated directly in Java.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What types of methods can an interface contain in Java?

A

Interfaces can contain abstract, default (Java 8+), and static methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What types of methods can an abstract class contain in Java?

A

Abstract classes can contain both abstract and concrete methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What type of fields can an interface have in Java?

A

Interfaces can only have public static final (constant) fields.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What type of fields can an abstract class have in Java?

A

Abstract classes can have any type of fields (instance variables, static variables, constants).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Does Java support multiple inheritance through interfaces?

A

Yes, a class can implement multiple interfaces.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Does Java support multiple inheritance through abstract classes?

A

No, a class can only extend one abstract class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Can an interface have constructors in Java?
No, interfaces cannot have constructors.
26
Can an abstract class have constructors in Java?
Yes, abstract classes can have constructors.
27
What is the implicit access modifier for interface methods?
Interface methods are implicitly public.
28
What access modifiers can abstract class methods have?
Abstract class methods can have any access modifier (public, protected, private).
29
What Java version introduced default methods in interfaces?
Default methods were introduced in Java 8.
30
Given this interface code, what will be printed when takeOff() is called on an Airplane object that doesn't override the method?
"Taking off" will be printed since the default implementation is used.
31
How would you call the static add method from this interface?
int sum = MathOperations.add(5, 3); (called directly on the interface)
32
What Java version introduced private methods in interfaces?
Private methods in interfaces were introduced in Java 9.
33
In this interface code, why is the log method private?
The log method is private to encapsulate the common logging implementation used by default methods within the interface.
34
What is the implicit modifier for methods declared in a Java interface?
public abstract (no need to explicitly declare them).
35
Why does final interface WalksOnEightLegs {} fail to compile?
Interfaces cannot be final because they must be implementable by classes.
36
Is abstract interface WalksOnTwoLegs {} valid? Why or why not?
Yes, but redundant—interfaces are implicitly abstract.
37
What happens if a class implements Climb but does not provide an implementation for getSpeed(int age)?
The class must be declared abstract, or it will fail to compile.
38
Given the Climb interface and FieldMouse class below, why is Float an allowed return type for getSpeed(int age)?
Because Float is a covariant return type (subclass of Number).
39
What access modifier must the implementing method use when overriding an interface method?
public (interface methods are implicitly public, and overriding cannot reduce visibility).
40
What is the purpose of the @Override annotation in interface method implementations?
Optional but recommended to clarify intent and catch errors (e.g., misspelled method names).
41
How does Java handle a class implementing two interfaces with the same method signature, like Climb and CanBurrow in the example?
A single implementation satisfies both interfaces.
42
If Owl extends Nocturnal, what must a class implementing Owl provide?
Implementations for both hunt() (inherited from Nocturnal) and flySilently().
43
Can an interface extend multiple interfaces in Java?
Yes, interfaces support multiple inheritance (e.g., interface A extends B, C).
44
What is the correct way to declare an interface in Java that includes a method swim() with no implementation?
java public interface Aquatic { void swim(); }
45
In the given code, how many interfaces does the Duck interface extend, and what are their names?
The Duck interface extends two interfaces: Aquatic and Flying.
46
What will happen if the Mallard class implements the Duck interface but fails to override one of its methods, such as quack()?
The code will not compile because a concrete class must provide implementations for all abstract methods inherited from interfaces.
47
Write the correct implementation of the Mallard class that properly overrides all methods required by the Duck interface.
java public class Mallard implements Duck { @Override public void swim() {} @Override public void takeOff() {} @Override public void quack() {} }
48
Why does the Duck interface not need to explicitly declare the swim() and takeOff() methods in its body?
Because Duck inherits these methods from the Aquatic and Flying interfaces via multiple interface inheritance.
49
What is the output of the following code if Mallard is instantiated and its methods are called?
The code compiles and runs without output because the overridden quack() method in Mallard is empty.
50
Identify the type of inheritance demonstrated in the code where Duck extends Aquatic and Flying.
This is an example of multiple interface inheritance, where an interface can extend multiple parent interfaces.
51
If the Flying interface added a new method land(), how would this affect the Mallard class?
The Mallard class would no longer compile unless it also overrides the new land() method.
52
What is the first rule of conflict resolution for default methods in Java interfaces when a class implements a method?
Class wins: If the class implements the method, interface defaults are ignored.
53
What is the second rule of conflict resolution for default methods when two interfaces provide competing defaults?
Most specific interface wins: The default from the more specific interface is used.
54
What is required when there is ambiguity between default methods from multiple interfaces, and neither is more specific?
Explicit override is required in the implementing class to resolve the ambiguity.
55
Given the following interfaces, what happens if class Bear does NOT override the eat() method?
The code will not compile because there is ambiguity between the two default eat() methods, requiring an explicit override in Bear.
56
In the following code, how does Bear explicitly resolve the default method conflict between Herbivore and Omnivore?
By overriding eat() and explicitly calling Omnivore.super.eat(), selecting Omnivore's default implementation.
57
What is the output of the following code?
The output is "Eating everything" because Omnivore's eat() implementation is explicitly called.
58
Why is the @Override annotation used in the Bear class's eat() method?
To indicate that the method is intentionally overriding a default method from one of its interfaces.
59
What syntax is used to explicitly call a default method from a specific interface in Java?
InterfaceName.super.methodName(), e.g., Omnivore.super.eat().
60
What is the correct way to call the static add method in the MathOperations interface, given the following code?
The method is called directly using the interface name: java int sum = MathOperations.add(3, 5);
61
Why can the add method in MathOperations be declared static in an interface? What is its purpose?
Static methods in interfaces provide utility methods that belong to the interface itself (not instances). They are used for operations that don’t depend on instance state, like the add method here.
62
In the Logger interface, why are the format and log methods declared private?
They are private to encapsulate helper logic used by the default method (logInfo), hiding implementation details from implementing classes.
63
What Java version introduced private methods in interfaces, and what problem do they solve?
Java 9 introduced private interface methods to reduce code duplication in default methods by extracting shared logic into reusable private methods.
64
In the Logger interface, what does the logInfo default method do, and how does it use the private methods?
The logInfo method prepends "INFO: " to the message, formats it with a timestamp (via format), and prints it (via log). Example output: text INFO: [2025-06-26T12:34:56Z] Hello
65
What would happen if a class implementing Logger tried to call the private format method directly?
It would cause a compilation error because private interface methods are only accessible within the interface itself.
66
Given the following interfaces, what is the correct way for HasBigEyes to extend both Nocturnal and CanFly?
java public interface HasBigEyes extends Nocturnal, CanFly { // Inherits both hunt() and flap() }
67
If Owl implements HasBigEyes, which two methods must it provide, and what access modifier must they have?
The Owl class must implement hunt() and flap(), both with the public modifier because interface methods are implicitly public abstract.
68
What happens if a class implements an interface but fails to provide an implementation for one of its abstract methods?
The class must be declared abstract, or it will not compile.
69
Given the following abstract classes and interfaces, which four methods must Swan implement?
Swan must implement: getType() (from Animal) canSwoop() (from Bird) fly() (from Fly) swim() (from Swim)
70
Why does the following code fail to compile?
Because Penguin is not abstract and does not implement the required canSwoop() method.
71
What is the access level of hunt() in the Nocturnal interface?
It is implicitly public abstract because all interface methods are public abstract by default.
72
Can an interface extend multiple interfaces in Java?
Yes, an interface can extend multiple interfaces (e.g., HasBigEyes extends Nocturnal, CanFly).
73
If a concrete class extends an abstract class and implements an interface, which methods must it provide?
It must implement all unimplemented abstract methods from both the abstract class and the interface(s).
74
What is wrong with the following CommonSeal class that causes it not to compile?
It fails to implement the abstract methods getTailLength() and getNumberOfWhiskers() inherited from the HasTail and HasWhiskers interfaces, which are required for concrete classes.
75
Why does this abstract class compile despite not implementing interface methods?
Abstract classes are not required to provide implementations for interface methods; the implementation can be deferred to concrete subclasses.
76
What two interface methods must the concrete CommonSeal class implement to compile correctly?
java @Override public int getTailLength() { return 3; } @Override public int getNumberOfWhiskers() { return 20; }
77
What access modifier must be used when implementing interface methods in a class, and why?
public – interface methods are implicitly public abstract, and overriding them with reduced visibility would violate the interface contract.
78
Which statement about interface extension is true?
Interfaces can extend multiple other interfaces and inherit all their abstract methods without providing implementations.
79
What three implementation options exist for abstract classes implementing interfaces?
Provide no implementations (defer to subclasses) Partially implement some interface methods Fully implement all interface methods
80
What is the key difference between abstract and concrete classes regarding interface implementation?
The first concrete class in an inheritance hierarchy must implement all unimplemented abstract methods from both parent classes and interfaces.
81
What would happen if HarborSeal were declared as follows?
It would not compile because interface method implementations must be public (the method is package-private here).
82
What is the correct way for an interface to inherit from another interface in Java? Include the code example.
An interface can extend another interface using the extends keyword. Example: java interface A {} interface B extends A {} // Valid: Interface extends interface
83
What is the correct way for a class to inherit from an interface in Java? Include the code example.
A class can implement an interface using the implements keyword. Example: java interface A {} class C implements A {} // Valid: Class implements interface
84
Why does class Y extends X {} fail to compile if X is an interface? Include the code example.
A class cannot extend an interface; it must use implements. Example: java interface X {} class Y extends X {} // Invalid: Class cannot extend interface (DOES NOT COMPILE)
85
Why does interface W extends Z {} fail to compile if Z is a class? Include the code example.
An interface cannot extend a class; it can only extend another interface. Example: java class Z {} interface W extends Z {} // Invalid: Interface cannot extend class (DOES NOT COMPILE)
86
What is the output of the following code, and why does it compile successfully despite both interfaces declaring eatPlants()?
Output: Eating plants9. It compiles because the eatPlants() methods in both interfaces have identical signatures (same return type int, same method name, and compatible parameter list (int)), so the Bear class can implement both with a single method.
87
In the given code, what would happen if Omnivore's eatPlants() method had a different parameter type (e.g., long)?
The code would fail to compile because the Bear class would need to implement both Herbivore.eatPlants(int) and Omnivore.eatPlants(long) separately, causing a conflict as they are no longer method signature-compatible.
88
Why is the @Override annotation used in the Bear class's eatPlants() method?
The @Override annotation ensures at compile-time that the method correctly overrides/implements the interface method(s). If the method signature doesn't match any interface method, the compiler will raise an error.
89
What principle of Java interfaces is demonstrated by the Bear class implementing both Herbivore and Omnivore with a single eatPlants() method?
It demonstrates that Java allows a class to implement multiple interfaces with compatible abstract methods (identical signatures), requiring only one concrete implementation.
90
How many abstract methods must the Bear class implement based on these interfaces?
Only one, because both interfaces declare abstract methods with the same signature (int eatPlants(int)), so a single implementation satisfies both.
91
Given the following interfaces, why does the Tiger class fail to compile?
The Tiger class fails to compile because it cannot implement both Herbivore and Omnivore due to incompatible method declarations. The eatPlants() methods have the same parameter types but different return types (void vs. int), making them neither overrides nor overloads.
92
What is the key requirement for method parameter types when implementing methods from multiple interfaces?
Method parameter types must match exactly when implementing methods from multiple interfaces.
93
Can a class implement two interfaces with methods that have the same name and parameters but different return types? Explain why or why not.
No, a class cannot implement two such interfaces because Java does not allow methods to differ only by return type (method overloading rules). The compiler cannot resolve which method to use.
94
What is the implicit modifier for variables declared in an interface?
Variables in an interface are implicitly public static final (constants).
95
What modifiers are implicitly applied to methods in an interface (excluding private/default/static methods)?
Interface methods are implicitly public abstract unless they are private, default, or static.
96
True or False: A default method in an interface must explicitly declare the public modifier.
False. default methods are implicitly public, so the modifier is optional.
97
What modifier is implicitly applied to an interface itself if not specified?
An interface is implicitly abstract, though writing it explicitly is optional.
98
Are static methods in interfaces implicitly public?
Yes, static methods in interfaces are implicitly public.
99
Can parameter names differ when implementing methods from interfaces, even if the types must match?
Yes, parameter names can differ as long as the types and order match exactly.
100
Is covariant return typing possible when implementing methods from two different interfaces in the same class?
No, covariant return types only apply to overrides in class hierarchies, not when implementing multiple interfaces with conflicting return types.
101
What is wrong with the following implementation of the Climb interface, and how would you fix it?
The reachTop() method in Climber has weaker access (package-private) than the interface's implicitly public method. To fix it, declare it as public: java public void reachTop() {}
102
Why does the following class C fail to compile, and what is the solution?
The class C fails because it inherits two methods with the same signature but incompatible return types (String vs. Integer). The solution is to redesign the interfaces to avoid this conflict.
103
What is the error in the following code, and why does it occur?
The error occurs because interface variables (VALUE) are implicitly public static final and cannot be reassigned. The solution is to treat them as constants and avoid modification.
104
What modifiers are implicitly applied to an abstract method in a Java interface, and what optional modifier can be added?
Abstract methods in interfaces are implicitly public, and the abstract modifier is optional.
105
What modifiers must a constant variable have in a Java interface, and what is required for its declaration?
Interface constants must be declared as public static final and must be initialized.
106
What is the difference between a default method and a static method in a Java interface regarding their implementation?
Both default and static methods must have bodies in interfaces, but default methods are instance methods while static methods are class-level.
107
What Java version introduced private methods in interfaces, and what is their implementation requirement?
Private methods in interfaces were introduced in Java 9+ and must have method bodies.
108
Analyze the following interface code and explain why the 'count' variable declaration doesn't compile:
It doesn't compile because interface variables must be public (implicitly public static final), and private is not allowed for variables.
109
In the following interface code, why does the 'step()' method declaration fail to compile?
It fails because interface methods must be public (or private for Java 9+ methods), and protected is not allowed.
110
What is wrong with the following method declaration in an interface, and which modifier causes the issue?
The final modifier is invalid because abstract methods (default in interfaces) cannot be final as they must be implementable by classes.
111
What modifiers are required for a private static method in a Java interface, and since which Java version is this allowed?
Private static methods in interfaces must be declared with both private and static modifiers, and this is allowed since Java 9.
112
Which of the following is a valid member type in a Java interface with all required modifiers: (a) abstract method, (b) protected constant, (c) private static method, (d) final default method?
(a) abstract method and (c) private static method (Java 9+) are valid. (b) and (d) are invalid due to modifier conflicts.
113
In the given code, why does the Webby class's play() method compile successfully when extending Husky?
It compiles because Webby's play() method has the same package-private access level as its parent abstract method in Husky.
114
What is the access level of the play() method in the Poodle interface, and why does this cause compilation to fail in Georgette?
The play() method in Poodle is implicitly public abstract. Georgette fails to compile because its implementation reduces visibility to package-private, which violates the interface contract.
115
Identify the key difference between method implementation rules when extending an abstract class (Husky) versus implementing an interface (Poodle), as shown in the code.
When extending an abstract class, the implementing method can match the parent's access level, but when implementing an interface, the method must be public (cannot reduce visibility from the interface's implicit public).
116
What would happen if you added public to Georgette's play() method declaration?
It would compile successfully because the method now matches the interface's required public access level.
117
Why is the play() method in Husky considered package-private, while in Poodle it's implicitly public?
In Husky, no explicit modifier makes it package-private, whereas interface methods are always public abstract by default (even without keywords).
118
Which of these class declarations contains a valid implementation of its parent's abstract method based on Java access rules?
Option A (Webby) is valid because it matches Husky's package-private access, while Option B (Georgette) fails by reducing Poodle's implicit public visibility.
119
What is a default method in a Java interface, and how is it declared? Provide the syntax example from the Swim interface.
A default method in a Java interface is a method with a default implementation (not abstract). It is declared using the default keyword. Example: java default void backstroke() { System.out.println("Swimming backstroke"); }
120
In the Swim interface, is the backstroke() method implicitly public, private, or protected? Explain why.
The backstroke() method is implicitly public because all interface methods (including default methods) are public by default.
121
What will the following code print if Swim's backstroke() is called?
It will print: text Swimming backstroke
122
What is a static method in a Java interface, and how is it declared? Provide the syntax example from the MathHelper interface.
A static method in a Java interface is a utility method that belongs to the interface itself (not instances). It is declared using the static keyword. Example: java static int square(int num) { return num * num; }
123
How would you call the square() method from the MathHelper interface? Write the correct invocation.
Since square() is static, it must be called via the interface name: java int result = MathHelper.square(5); // Returns 25
124
True or False: A static method in an interface can be overridden by implementing classes.
False. Static methods in interfaces are not inherited by implementing classes and cannot be overridden.
125
Which Java version introduced default and static methods in interfaces, and why were they added?
Java 8 introduced them to enable interface evolution (adding new methods without breaking existing implementations) and support utility methods in interfaces.
126
Identify the error in this interface declaration:
default methods cannot be private. They must be public (explicitly or implicitly).
127
What modifiers are implicitly applied to a constant variable declared in a Java interface?
public static final
128
What happens if a constant in a Java interface is not initialized?
It causes a compilation error because constants in interfaces must be initialized.
129
What is the implicit modifier for abstract methods in a Java interface?
public abstract
130
Write the correct syntax for an abstract method doAction() in a Java interface.
java void doAction(); // public abstract implied
131
What is the purpose of default methods in Java interfaces?
To provide backward compatibility by allowing new methods to be added without breaking existing implementations.
132
What keyword must be used when declaring a default method in an interface, and what modifier is implicitly applied?
The default keyword must be used, and it's implicitly public.
133
Write a valid default method named log() that prints "Action logged" to the console.
java default void log() { System.out.println("Action logged"); }
134
How are static methods in interfaces different from default methods in terms of invocation?
Static methods are called via the interface name (e.g., InterfaceName.method()), while default methods are instance methods.
135
Write a static interface method named print() that displays "Interface method".
java static void print() { System.out.println("Interface method"); }
136
Since which Java version can interfaces have private methods, and what are their two types?
Java 9+, with two types: private instance methods and private static methods.
137
What is the main restriction for private methods in interfaces?
They can only be used within the interface they're declared in (as helper methods).
138
Write a private instance method helper() and a private static method setup() in an interface.
java private void helper() { /* instance helper */ } private static void setup() { /* static helper */ }
139
True or False: Default methods in interfaces must be overridden by implementing classes.
False. They can be overridden but it's not required.
140
Which interface member type cannot have a method body?
Abstract methods cannot have a body (they end with a semicolon).
141
What will be the output when the following code is executed?
12.2 (The overridden getTemperature() method in the Snake class is called)
142
What will be the output when the following code is executed?
true (The static isCold() method is called from the interface with a temperature below 15.0)
143
What type of method in an interface must be implemented by any class that implements the interface?
Abstract methods (like hasScales() in the IsColdBlooded interface)
144
What is the purpose of the default keyword in an interface method declaration?
It provides an optional implementation that implementing classes can use or override (like getTemperature() in the IsColdBlooded interface)
145
Can a class override a static method from an interface it implements?
No (as shown in the Snake class which cannot override isCold())
146
What access modifiers are supported for interface members in Java?
public (implicit), private (Java 9+ for methods), and none (only for private members)
147
What access modifiers are NOT supported for interface members?
protected and package-private (would break backward compatibility)
148
What is the return type of the hasScales() method in the IsColdBlooded interface?
boolean
149
What will be the default return value if a class implements IsColdBlooded but doesn't override the getTemperature() method?
10.0 (the default implementation in the interface)
150
What is the threshold temperature used in the IsColdBlooded.isCold() method to determine if something is cold?
15.0 (returns true if the temperature is below this value)
151
What is wrong with the method declaration protected void badIdea(); in the interface InvalidExample?
Interface methods cannot be declared as protected. All interface methods are implicitly public, so this declaration would cause a compilation error.
152
What is the actual access level of void packagePrivateMethod(); in the interface InvalidExample?
Despite having no explicit modifier, packagePrivateMethod() is implicitly public because all interface methods are public by default.
153
Why does the method declaration private abstract void why(); in InvalidExample fail to compile?
Interface methods cannot be private and abstract at the same time. private methods in interfaces (allowed since Java 9) must be concrete (have a body), and abstract methods cannot be private.
154
Which keyword combinations are invalid for interface method declarations in Java, based on the InvalidExample interface?
protected and private abstract are invalid. Interface methods are implicitly public, and private methods must be concrete (non-abstract).
155
Given the following interface declaration, which line(s) would cause compilation errors and why?
Line 1 (cannot use protected) and Line 3 (cannot combine private and abstract). Line 2 is valid (implicitly public).
156
What is the first core rule for default methods in Java interfaces?
Default methods can only be declared within interfaces.
157
What keyword must be used when declaring a default method in a Java interface, and what must it include?
The default keyword must be used, and the method must have a body.
158
What is the visibility/access level of default methods in interfaces, and can they be declared as private or protected?
Default methods are always public and cannot be declared as private or protected.
159
Which three modifiers cannot be used with default methods in interfaces?
Default methods cannot be abstract, final, or static.
160
Analyze this code and explain why it doesn't compile:
It doesn't compile because the default method eatMeat() is missing its method body (implementation).
161
Identify the compilation error in this interface code:
It doesn't compile because the method is missing the default keyword despite having an implementation.
162
Why does this interface declaration fail to compile?
It doesn't compile because default methods cannot be declared as private (they must be public).
163
What is the "diamond problem" in Java as it relates to default methods?
It's when a class implements two interfaces with default methods of the same signature, creating ambiguity.
164
Why does this class declaration fail to compile?
It doesn't compile because both Walk and Run interfaces have a getSpeed() default method, creating ambiguity (the diamond problem).
165
What is the correct way to resolve a default method conflict between two interfaces? Show the solution code for the Cat class implementing both Walk and Run.
The class must override the conflicting method. Solution: java public class Cat implements Walk, Run { @Override public int getSpeed() { return Run.super.getSpeed(); // Explicitly choose Run's version } }
166
In the solution to the diamond problem, what does Run.super.getSpeed() specifically accomplish?
It explicitly calls the getSpeed() default method implementation from the Run interface.
167
What is the output of the following code if a Bird object calls takeOff()?
The output is Default takeoff because Bird uses the default implementation of takeOff() from the Fly interface.
168
What is the output of the following code if an Airplane object calls takeOff()?
The output is Airplane takeoff because Airplane overrides the default takeOff() method from the Fly interface.
169
In Java, is it valid for a class to implement an interface with a default method without overriding it? Provide an example.
Yes, it is valid. The Bird class uses the default implementation of takeOff() from the Fly interface without overriding it.
170
What keyword is used in an interface to provide a default implementation of a method? Include the syntax.
The default keyword is used. The syntax is: java default void methodName() { /* implementation */ }
171
What annotation should be used when overriding a default method from an interface? Provide an example.
The @Override annotation should be used, as shown in the Airplane class overriding takeOff().
172
If a class implements an interface with a default method but does not override it, which implementation is executed when the method is called?
The default implementation from the interface ("Default takeoff") is executed.
173
Given the following code, why does Dance.getRhythm() fail to compile, while this.getRhythm() is valid?
Dance.getRhythm() fails because default methods are instance methods, not static methods, and must be called on an instance (e.g., this).
174
What is the output of the following code, and why?
The output is "Mammal" because the most specific interface (Mammal) overrides the parent interface's default method.
175
True or False: A class inheriting two interfaces with conflicting default methods must explicitly override the method to resolve the conflict.
True. If two interfaces provide conflicting default methods, the implementing class must override the method to avoid a compilation error.
176
In the context of default methods, what does the @Override annotation in the Mammal interface indicate?
It explicitly indicates that the describe() default method in Mammal overrides the describe() method from the parent Animal interface.
177
Which Java feature allows interfaces to provide method implementations without breaking existing classes that implement them?
Default methods (using the default keyword) in interfaces.
178
In the given Swimmer interface, what is the difference between the breatheUnderwater() method and the stroke() method in terms of their implementation requirements?
breatheUnderwater() is an abstract method (no implementation, no default keyword), so any implementing class like Fish must override it. stroke() is a default method (has implementation, marked with default), making it optional for implementing classes to override.
179
What will happen if the Fish class does NOT override the stroke() method from the Swimmer interface?
The Fish class will inherit the default implementation of stroke() from the Swimmer interface, printing "Default stroke" when called. No compilation error occurs.
180
Write the correct syntax to declare an abstract method dive() in the Swimmer interface (no implementation).
java void dive(); // No body or default keyword
181
What keyword is used in an interface to provide a default implementation of a method that implementing classes can optionally override?
The default keyword (e.g., default void stroke() { ... } in the Swimmer interface).
182
In the Fish class implementation, what does the @Override annotation indicate about the breatheUnderwater() method?
It explicitly states that breatheUnderwater() is overriding an abstract method from the Swimmer interface. The compiler will verify that the method signature matches.
183
Why does the Fish class NOT produce a compilation error despite not implementing the stroke() method?
Because stroke() is a default method in the Swimmer interface, which provides a ready-to-use implementation that the Fish class inherits automatically.
184
What is the compilation error in the following code, and why does it occur?
The error occurs because print() is an instance method (default method) of the Wrong interface, but it is being called statically (Wrong.print()). Default methods must be invoked on an instance of the interface, not on the interface itself.
185
Why does the following code fail to compile?
The code fails to compile because class C inherits two conflicting default implementations of foo() from interfaces A and B. The class must explicitly override foo() to resolve the ambiguity.
186
What is the compilation error in the following code, and what is the rule being violated?
The error occurs because the method() in Child reduces the visibility (package-private) compared to the default (public) method in Parent. Overriding methods cannot have weaker access privileges than the method they override.
187
What keyword is required when declaring a static method in a Java interface, and what is its implicit access modifier?
The static keyword is required, and the method is implicitly public.
188
What will happen if you try to call a static interface method directly from a class that implements the interface without using the interface name? (Provide an example)
It will cause a compilation error. Example: java public class Bunny implements Hop { public void printDetails() { System.out.println(getJumpHeight()); // DOES NOT COMPILE } } The correct way is Hop.getJumpHeight().
189
Can a static method in a Java interface be declared as abstract or final?
No, static interface methods cannot be abstract or final.
190
How do you call a static method defined in an interface from an implementing class?
You must use the interface name (e.g., Hop.getJumpHeight()).
191
What happens if a class implements two interfaces with conflicting default methods, and how can this be resolved?
The class must override the conflicting method. Example: java public class Cat implements Walk, Run { @Override public int getSpeed() { return 1; // New implementation } }
192
What is the correct syntax to access a hidden default method implementation from an interface in an overriding class?
Use InterfaceName.super.methodName(). Example: java public int getOriginalWalkSpeed() { return Walk.super.getSpeed(); // Accesses Walk's default }
193
How do default methods differ from static methods in interfaces regarding inheritance?
Default methods are inherited by implementing classes, while static methods are not.
194
What is the implicit access modifier for both default and static methods in a Java interface?
Both are implicitly public.
195
Can a static method in an interface be overridden by an implementing class?
No, static interface methods cannot be overridden.
196
What is the key syntax difference when calling a default method vs. a static method from an interface?
Default methods use instance.method() or InterfaceName.super.method(), while static methods use InterfaceName.method().
197
Why does the following code fail to compile?
The static method getJumpHeight() must be called using the interface name: Hop.getJumpHeight().
198
In the Rabbit class example, why does int height = getJumpHeight(); fail to compile, and what is the correct way to call this static method from the Hop interface?
It fails because static interface methods must be called with the interface name. The correct way is: int height = Hop.getJumpHeight();
199
What is the output of the following code, and why does the HighJump class's getJumpHeight() method not override Hop's version?
The output is 10. The HighJump method hides rather than overrides Hop's static method because static methods cannot be overridden - they are bound at compile-time.
200
Why does the getSpeed() method in the Cheetah class fail to compile, and what is the required fix?
It fails because the implementing class cannot reduce the visibility of the interface's default method (from public to package-private). The fix is to make it public: public int getSpeed() { return 20; }
201
Which of these correctly demonstrates the proper way to implement a static method from an interface in Java?
B) class A implements B { void method() { B.method(); } } is correct because static interface methods must be called using the interface name.
202
What principle of Java interfaces is violated when a class tries to override a static method from an interface?
The principle that static methods cannot be overridden (they can only be hidden). Static methods are bound at compile-time through static binding, not runtime polymorphism.
203
In the given Schedule interface, what type of method is haveBreakfast() and which methods can call it?
haveBreakfast() is a private non-static method. It can only be called by default methods (like wakeUp()) and other private non-static methods within the interface.
204
What will be the output of Schedule.workOut() when called, based on the checkTime() implementation?
It will print "You're late!" because the hardcoded hour (18) in workOut() is greater than 17.
205
Why can't the private static checkTime() method access instance-specific state?
Because static methods belong to the interface itself rather than instances, and cannot access non-static fields/methods.
206
Identify the accessibility rule violation in this attempted call: new MySchedule().haveBreakfast()
This violates accessibility rules because private interface methods (like haveBreakfast()) cannot be called from implementing classes - they're only accessible within the interface.
207
What makes the checkTime() method a utility method in the Schedule interface?
It's a private static method used by multiple other methods (wakeUp(), haveBreakfast(), workOut()) for shared time-checking functionality.
208
Given this code from the interface, what will wakeUp() print when hour=7 is passed to checkTime()?
It will print "You have 10 hours left" (17 - 7 = 10).
209
Which interface method type must be called using the interface name (e.g., Schedule.staticMethod())?
Static methods must be called using the interface name, as they belong to the interface rather than instances.
210
What is the key difference between private static and private non-static methods in interfaces regarding what they can access?
Private static methods can be called by any method in the interface but cannot access instance state, while private non-static methods can access instance state but only through default methods.
211
What is wrong with this attempt to call interface private methods externally in the Planner class?
Both calls are invalid because: 1) haveBreakfast() is a private instance method that can't be called from implementing classes, and 2) checkTime() is a private static method that can't be called externally even with the interface name.
212
Why does this static method call to instanceMethod() fail to compile?
Static methods cannot call non-static private methods because instance methods require an object instance, while static methods don't have access to 'this' reference.
213
What is missing from this private interface method declaration that causes a compilation error?
The method body is missing. Private interface methods must have implementations (bodies) since Java 9, unlike abstract methods in interfaces.
214
In the Schedule interface example, which methods can call the private haveBreakfast() method?
Only non-static methods within the same interface (default methods and other private non-static methods) can call haveBreakfast().
215
What is the key difference in accessibility between private static and private non-static methods in interfaces?
Private static methods can be called by any method in the interface (static or non-static), while private non-static methods can only be called by default and other private non-static methods.
216
What will this interface code output when wakeUp() is called, assuming checkTime() prints messages?
It will print: "You have 10 hours left" (from checkTime(7)) "You have 8 hours left" (from checkTime(9) in haveBreakfast())
217
What are three main reasons to use private methods in interfaces?
1) Code reuse between default methods, 2) Encapsulation of implementation details, 3) Improved maintainability through better organization.
218
In the FinancialCalculator interface, why is getInterestRate() declared as private static?
Because it's a utility method that doesn't need instance state and should be shared across all methods in the interface while being hidden from external callers.
219
What best practice is demonstrated by this Validator interface code?
Breaking down complex validation into smaller, focused private methods that each handle a single responsibility while hiding implementation details.
220
What makes this recursive traversal in TreeWalker interface possible?
The default method traverse() can recursively call itself while using private methods to handle implementation details, demonstrating how private methods enable complex algorithms in interfaces.
221
In the ZooTrainTour interface, why does the line playHorn(); in the slowDown() method cause a compilation error?
Because slowDown() is a static method and cannot call the instance method playHorn(). Static methods can only call other static methods or access static fields directly.
222
In the ZooTrainTour interface, is the call ride(); valid inside the playHorn() default method? Why or why not?
Yes, it is valid because playHorn() is an instance method, and private static methods like ride() are accessible within the same interface, regardless of context.
223
What is the output of the following code snippet, assuming it compiles?
The output will be "WINTER" because enums implicitly override toString() to return the name of the constant.
224
What is wrong with the following enum declaration?
The enum is missing a constructor to initialize mass and radius. A constructor like Planet(double mass, double radius) is required to assign values to these fields when the constants are declared.
225
Which of the following is true about enum constants in Java?
Enum constants are type-safe, implicitly extend java.lang.Enum, and can have methods, fields, and constructors. They represent a fixed set of values known at compile time.
226
In the Planet enum, what does the surfaceGravity() method calculate?
It calculates the surface gravity of the planet using the formula for gravitational force: G × m a s s r a d i u s 2 G× radius 2 mass ​ , where G G is the gravitational constant.
227
Which interface member types can be accessed by inheriting classes without an instance of the interface?
Constants (public static final fields), static methods, and private static methods can be accessed without an instance. Abstract and default methods require an instance.
228
Why can't a private method in an interface be called from an inheriting class?
Private methods are only accessible within the interface itself and are not inherited by implementing classes, as per Java's access control rules.
229
What is the purpose of the default keyword in an interface method declaration?
The default keyword allows the interface to provide a method implementation that inheriting classes can use or override, enabling backward compatibility when new methods are added to interfaces.
230
What are three common use cases for enums in Java?
1) Days of week (MONDAY, TUESDAY), 2) Application states (STARTED, RUNNING, STOPPED), 3) Fixed categories (BRONZE, SILVER, GOLD).
231
What naming convention should be used for enum values in Java?
Enum values should use uppercase letters (e.g., MONDAY, RUNNING, GOLD).
232
What is wrong with this enum instantiation attempt?
Enums cannot be instantiated with new because they have fixed instances (RED, GREEN in this case).
233
In the Operation enum example, why is the apply method declared abstract?
The apply method is abstract to force each enum constant (PLUS, MINUS) to provide its own implementation of the method.
234
Why does this interface code fail to compile?
Static methods cannot call instance methods (method()) directly because instance methods require an object instance.
235
What is wrong with this private interface method usage?
Private interface methods cannot be called from static methods, only from default or other private methods.
236
What is one key difference between interfaces and enums regarding inheritance?
Interfaces support multiple inheritance (a class can implement multiple interfaces), while enums only support single inheritance (all enums implicitly extend java.lang.Enum).
237
In the Operation enum example, what design pattern is being demonstrated by having each enum constant provide its own apply method implementation?
The Strategy pattern, where each enum constant represents a different strategy for performing the operation.
238
What is the purpose of the validate() method in the Formatter interface, and why is it declared as private?
The validate() method checks if the input is null (throwing IllegalArgumentException if true). It's private because it's a helper method only meant to be used within the interface's default method (formatJSON), not by implementing classes.
239
In the Formatter interface, what will formatJSON(" HELLO ") return, and why?
It will return "{hello}". The process() method trims whitespace and converts to lowercase, and formatJSON wraps the result in curly braces.
240
Why can the process() method in Formatter be declared as static, while validate() cannot?
process() is static because it doesn't depend on instance state. validate() could also be static (since it doesn't use instance state either), but the author chose to make it an instance method (private).
241
What is the output of TrafficLight.RED.getAction() and why?
Output is "Stop". Each enum constant (RED, YELLOW, GREEN) is initialized with its corresponding action string via the constructor.
242
Identify the three key components of the TrafficLight enum declaration that give it state and behavior.
Instance field: private final String action Constructor: TrafficLight(String action) Behavior method: public String getAction()
243
What would happen if you tried to call Formatter.process("test") from another class?
It would fail to compile. process() is a private static method in the Formatter interface, so it's only accessible within the interface itself.
244
How many instances of the TrafficLight enum exist at runtime, and how are they created?
Three instances (RED, YELLOW, GREEN). They are created when the enum is loaded, using the constructor TrafficLight(String action).
245
What is the data type of TrafficLight.GREEN, and what methods can be called on it?
Its type is TrafficLight. You can call getAction() (instance method) or any inherited Enum methods like name() or ordinal().
246
Why does the Formatter interface use a default method (formatJSON) instead of an abstract method?
A default method provides a default implementation so implementing classes don’t have to override it, while still allowing them to do so if needed.
247
What is the correct syntax to declare a simple enum named Season with the values WINTER, SPRING, SUMMER, and FALL?
java public enum Season { WINTER, SPRING, SUMMER, FALL }
248
In the enum declaration public enum Season { WINTER, SPRING, SUMMER, FALL }, is the semicolon at the end required?
No, the semicolon is optional for simple enums (those without additional methods or fields).
249
Given the following code, what will be printed?
SUMMER
250
What is the output of the following code?
true
251
What keyword(s) must be used to declare an enum in Java?
public enum (or just enum if not public).
252
In Java, how are enum constants (values) separated inside the enum declaration?
By commas (e.g., WINTER, SPRING, SUMMER, FALL).
253
What is the name of the enum in this declaration?
Season
254
What type of enum is the following, and why?
A simple enum because it only contains a list of constants without additional methods, fields, or constructors.
255
What error occurs when attempting to make one enum extend another, as shown in this code?
Compilation error - enums cannot extend other enums in Java.
256
What happens if you try to modify enum values after their creation in Java?
Compilation error - enum values are fixed and cannot be modified after creation.
257
What Java feature can enums implement despite not being able to extend classes?
Enums can implement interfaces, though they cannot extend classes.
258
Given this enum iteration code, what does values() return?
It returns an array containing all values of the enum in declaration order.
259
What will this code print?
It will print "WINTER" - the exact name of the enum constant as a String.
260
What does the ordinal() method return for this enum constant?
It returns 1 - the zero-based position of SPRING in the enum declaration.
261
If FALL is declared after SUMMER in an enum, what ordinal value will it have?
It will have ordinal value 3 (assuming WINTER=0, SPRING=1, SUMMER=2).
262
What is the relationship between an enum's declaration order and its ordinal values?
The ordinal values are assigned sequentially starting from 0 based on the declaration order.
263
What does the valueOf() method do when called on an enum like Season.valueOf("SUMMER"), and what is a key requirement for the String argument?
It converts the String to the corresponding enum value. The String must match the enum constant exactly, including case sensitivity (e.g., "SUMMER" works, but "summer" throws IllegalArgumentException).
264
What exception is thrown if you call Season.valueOf("summer") when the enum only has a constant named SUMMER?
IllegalArgumentException because the String does not match any enum constant exactly (case mismatch).
265
Does Season.valueOf("SUMMER") create a new enum value or return an existing one?
It returns the existing enum value; it does not create a new one.
266
In the switch statement below, what will getWeather(Season.SPRING) return?
"Just right" because SPRING falls under the combined case label SPRING, FALL.
267
Why is the following code invalid for a switch statement using the Season enum?
Enum switch cases must use the unqualified enum constant name (e.g., SUMMER), not a String literal like "SUMMER".
268
What is the output of this code if Season.valueOf("AUTUMN") is called but the Season enum has no AUTUMN constant?
It throws an IllegalArgumentException because the String does not match any enum constant.
269
What is the output of the following code?
The output is: text Constructing.Constructing.Constructing.Constructing.High (Explanation: The constructor runs for each enum value when the enum is loaded, then printVisitors() prints "High" for SUMMER.)
270
Why does the SeasonWithVisitors enum require a semicolon after its values (WINTER, SPRING, SUMMER, FALL)?
The semicolon is required because the enum contains additional code (constructor, methods, fields) after the values list.
271
What happens if you omit the private modifier in the SeasonWithVisitors constructor?
The code fails to compile because enum constructors must be private (explicitly or implicitly).
272
What is the purpose of the visitors instance variable in SeasonWithVisitors?
It stores the visitor data (e.g., "Low", "Medium") for each enum constant (WINTER, SPRING, etc.).
273
How would you modify SeasonWithVisitors to print the static DESCRIPTION field along with visitor data?
The modified printVisitors() method would output: text Weather enum: High // (if called on SUMMER)
274
Which rule applies to the order of declarations in a complex enum like SeasonWithVisitors?
Enum values must be declared first, before any constructors, methods, or fields.
275
What interface does SeasonWithVisitors implement, and what method does it override?
It implements Visitors and overrides printVisitors().
276
What is the output if you call SeasonWithVisitors.WINTER.printVisitors()?
The output is: text Low
277
Why is the visitors field in SeasonWithVisitors declared final?
To make it immutable, ensuring each enum constant’s visitor data cannot change after initialization.
278
What is the best practice for declaring variables in an enum and why? Include the code example.
Best practice is to make enum variables final (immutable). Example: java private final String visitors; // Good - immutable Reason: Enum values are shared across the program, and mutable variables could cause unexpected problems.
279
What is wrong with this enum variable declaration?
The variable is mutable (not final), which is bad practice for enum variables as they are shared across the program.
280
What is the access modifier for all enum constructors in Java?
All enum constructors are automatically private.
281
What will this code print and why?
It will print: "start,Constructor called,end". The constructor is called only once when the enum value is first used.
282
How many times is an enum constructor called for a particular enum value during program execution?
Only once - when the enum value is first used/loaded.
283
What is the output of this code and why?
Output: "start,init,end". The constructor is called only once when Test.A is first accessed.
284
Which of these enum constructor declarations would compile in Java?
Only b) private Season() {} and d) Season() {} would compile, as all enum constructors are automatically private.
285
What types of methods can enums have in Java?
Enums can have regular methods just like classes, including instance methods and static methods.
286
What will the following code print?
It will print: "It's SUMMER"
287
In the SeasonWithHours enum, why is the getHours() method declared as abstract?
The getHours() method is abstract to force each enum value to provide its own implementation, ensuring value-specific behavior.
288
What happens if you omit the getHours() implementation for one of the values in the SeasonWithHours enum?
The code will not compile because each enum value must implement all abstract methods declared in the enum.
289
What is the output of this enum usage?
It returns the string "9am-7pm"
290
Why are enum constructors implicitly private in Java?
Enum constructors are implicitly private to prevent additional instances from being created, ensuring only the predefined constants exist.
291
What design pattern is demonstrated by the SeasonWithHours enum where each value provides its own method implementation?
It demonstrates the strategy pattern, where each enum value encapsulates different behavior.
292
How does Java ensure enum immutability?
Enums are inherently immutable because: Their instances (values) are fixed at compile-time All fields should be final Constructors are private
293
What is the relationship between enum values and their constant-specific method implementations?
Each enum value behaves like an anonymous subclass that implements the enum's abstract methods.
294
Which line in this enum makes it compile successfully despite having abstract methods?
The public abstract String getHours(); declaration ensures all values implement the method.
295
What would happen if you tried to add a new enum value at runtime using reflection?
It would throw an exception because enums are designed to be immutable with fixed constants.
296
Given the SeasonWithTimes enum, what will SeasonWithTimes.WINTER.getHours() return?
It will return "10am-3pm" because the WINTER enum constant overrides the getHours() method.
297
What will SeasonWithTimes.SPRING.getHours() return, and why?
It will return "9am-5pm" because SPRING uses the default getHours() method defined in the enum.
298
Identify a syntax error in the following enum constant declaration from SeasonWithTimes:
The string literal uses " instead of ". The correct syntax should be: java WINTER { public String getHours() { return "10am-3pm"; } // Missing semicolon and incorrect quote }
299
How does the SeasonWithTimes enum ensure that SPRING and FALL share the same hours?
They do not override getHours(), so they use the default implementation provided in the enum: java public String getHours() { return "9am-5pm"; }
300
What is a key benefit of using an enum with method overrides, as shown in SeasonWithTimes?
It allows special cases (like WINTER and SUMMER) to have custom behavior while keeping a default implementation for others (SPRING and FALL), making the code cleaner and more maintainable.
301
What happens if you call getHours() on an enum constant that does not override the method and no default implementation exists?
The code would not compile because the enum must either provide a default getHours() method or each constant must implement its own.
302
Which enum constants in SeasonWithTimes use the default getHours() implementation?
SPRING and FALL use the default implementation.
303
What is the purpose of the sealed keyword in Java class declarations?
The sealed keyword marks a class as restricted, allowing only permitted classes to extend it.
304
What is the correct order of modifiers when declaring a sealed class in Java?
The sealed modifier must come before class. Example: java public sealed class Frog {} // Correct sealed public class Frog {} // Also correct
305
Identify the error in this sealed class declaration:
The sealed modifier is in the wrong position. It should be: java public sealed class Frog {}
306
What modifier is required for all subclasses of a sealed class in Java?
Subclasses must be declared as either final, sealed, or non-sealed.
307
What will happen if you try to extend a sealed class without including it in the permits clause?
This will cause a compilation error because Tiger is not listed in Mammal's permits clause.
308
What is the purpose of the non-sealed modifier when extending a sealed class?
non-sealed allows a subclass of a sealed class to be extended further by any other class.
309
What is the difference between enums and sealed classes in terms of extensibility?
Enums are completely fixed, while sealed classes allow controlled extension through permitted subclasses.
310
Which Java feature works particularly well with sealed classes for exhaustive pattern matching?
Switch expressions work well with sealed classes for exhaustive pattern matching.
311
What is missing from this sealed class declaration that will cause a compilation error?
The Car class is missing a required modifier (final, sealed, or non-sealed).
312
Which of these is a valid reason to use sealed classes instead of enums?
When you need complex class hierarchies with full class capabilities rather than simple, predefined values.
313
What is the purpose of the permits keyword in sealed class declarations?
The permits keyword lists the allowed subclasses that can extend the sealed class.
314
Given this code:
The Panda class can be extended further because it's declared as non-sealed.
315
What are the three possible modifiers for subclasses of a sealed class?
final, sealed, and non-sealed.
316
What are the three requirements for a subclass to properly extend a sealed class in Java?
1) Must explicitly extend the sealed class, 2) Must be in the same package (without modules), 3) Must declare exactly one modifier (final, sealed, or non-sealed).
317
Identify the error in this sealed class declaration: public class sealed Penguin {}
The sealed modifier must come before the class keyword. Correct form: public sealed class Penguin {}
318
What will happen when compiling this code?
Compilation error - Gazelle is declared final and cannot be extended by DamaGazelle.
319
In this hierarchy, which classes can be extended and by what?
Fish can only be extended by ClownFish. ClownFish can only be extended by OrangeClownFish. OrangeClownFish cannot be extended (final).
320
Why does this code compile successfully?
Because Car is declared non-sealed, allowing any class (like SportsCar) to extend it.
321
What is the compilation error in this code?
Parrot class is missing a required modifier (final, sealed, or non-sealed).
322
Why does this code fail to compile?
The classes are in different packages, and without modules, sealed classes and their permitted subclasses must be in the same package.
323
What are the four main benefits of using sealed classes in Java?
1) Controlled inheritance, 2) Better pattern matching with switch, 3) Clear documentation of design intent, 4) Safety by preventing unknown subclasses.
324
In this payment system example, which classes can be extended and why?
PayPal can be extended (non-sealed) - as shown by BusinessPayPal. BankTransfer can only be extended by ACHTransfer (sealed). CreditCard and ACHTransfer cannot be extended (final).
325
What modifier would you use if you want a subclass to be extendable by any other class?
The non-sealed modifier.
326
What is the purpose of the sealed keyword in public sealed class Animal permits Mammal, Bird, Reptile?
It restricts which classes can extend Animal to only Mammal, Bird, and Reptile.
327
Given the Mammal class public final class Mammal extends Animal { public void makeSound() { System.out.println("Mammal sound"); } }, why can't we create a subclass of Mammal?
Because Mammal is declared as final, which prevents any further inheritance.
328
What does the non-sealed modifier mean in public non-sealed class Bird extends Animal?
It means Bird can be extended by any number of subclasses (unrestricted inheritance).
329
In the Reptile hierarchy, why can't we create a new class class Turtle extends Reptile?
Because Reptile is sealed and only permits Snake and Lizard as subclasses (permits Snake, Lizard).
330
What will be printed when this code executes?
"Chirp!" (because Bird's implementation of makeSound() is called).
331
In the PaymentMethod hierarchy, why can we create SWIFTTransfer as a subclass of BankTransfer?
Because BankTransfer is declared as non-sealed, allowing unrestricted subclassing.
332
Given this code:
Because CreditCard is sealed and only permits Visa and MasterCard as subclasses.
333
What is the output of:
"Processing MasterCard: 100.5"
334
In the Animal hierarchy, which classes are direct permitted subclasses of Animal?
Mammal, Bird, and Reptile (as specified in the permits clause).
335
What modifier would you use if you want a sealed class's subclass to allow unlimited further extensions?
non-sealed (as shown in the Bird and BankTransfer examples).
336
Given the PaymentMethod hierarchy, which class is the parent of both Visa and MasterCard?
CreditCard (they both directly extend CreditCard).
337
What is wrong with this attempted class declaration?
It's invalid because CreditCard is sealed and doesn't permit Discover as a subclass.
338
In the Reptile hierarchy, what is the inheritance relationship between Snake and Animal?
Snake → Reptile → Animal (multi-level inheritance).
339
Why does the Animal class declare public abstract void makeSound()?
Because Animal is abstract (implied by having abstract methods) and wants to force subclasses to implement sound behavior.
340
What is the purpose of declaring CustomControl as non-sealed in the given example?
It allows CustomControl to be further extended by other classes (like FancyButton and AnimatedSlider), while still being part of the sealed hierarchy rooted at UIControl.
341
What will be the output when new FancyButton().render() is called?
text Rendering base custom control Adding fancy effects
342
Why are Button and TextField declared as final in this example?
To prevent any further extension of these classes, ensuring their behavior remains fixed as core UI controls.
343
What would happen if you tried to create a class ImageControl extends UIControl without including it in the permits clause?
It would cause a compilation error because UIControl is sealed and only permits specific subclasses (Button, TextField, CustomControl).
344
Identify the keyword that allows FancyButton and AnimatedSlider to legally extend CustomControl:
non-sealed (used in CustomControl's declaration).
345
What is the purpose of the permits keyword in sealed class UIControl?
It explicitly lists which classes are allowed to extend UIControl (Button, TextField, CustomControl in this case).
346
How does the sealed/non-sealed pattern in this example help framework authors?
It gives them control over which parts of the hierarchy can be extended (CustomControl) and which remain closed (Button, TextField).
347
What is wrong with this attempted subclass of the sealed hierarchy:
It fails to compile because UIControl is sealed and IllegalControl isn't listed in its permits clause.
348
In the FancyButton class, what does super.render() accomplish?
It invokes the render() method from the parent class (CustomControl) before executing its own additional logic.
349
Why might a developer choose this sealed/non-sealed approach over making all classes final?
It provides a controlled extension point (CustomControl) while keeping core components (Button, TextField) closed for modification.
350
Given this sealed class declaration, which subclass declaration will cause a compile error due to a missing modifier?
java public class Motorcycle extends Vehicle {} // Missing modifier (must be final, sealed, or non-sealed)
351
Which modifier in this subclass declaration is invalid for extending a sealed class?
protected is invalid (only final, sealed, or non-sealed are permitted when extending sealed types)
352
Why does this subclass declaration of a sealed class produce a compile error?
static is not allowed when extending sealed classes (only final, sealed, or non-sealed are permitted)
353
What is wrong with this interface declaration that extends a sealed interface?
Interfaces cannot be declared final (they're implicitly abstract)
354
Which modifier combination in this interface declaration would cause a compile error when extending a sealed interface?
private is not allowed (interfaces cannot be private)
355
What three modifiers must a subclass of a sealed class declare exactly one of?
final, sealed, or non-sealed
356
True or False: When extending a sealed type, you can combine access modifiers like public with the required sealed/final/non-sealed modifier.
False (no other access modifiers are allowed when extending sealed types)
357
Why can't interfaces be declared final in Java?
Because interfaces are implicitly abstract by nature
358
Given this sealed class declaration, which subclass declaration will cause a compile error due to a missing modifier?
java public class Motorcycle extends Vehicle {} // Missing modifier (must be final, sealed, or non-sealed)
359
Which modifier in this subclass declaration is invalid for extending a sealed class?
protected is invalid (only final, sealed, or non-sealed are permitted when extending sealed types)
360
Why does this subclass declaration of a sealed class produce a compile error?
static is not allowed when extending sealed classes (only final, sealed, or non-sealed are permitted)
361
What is wrong with this interface declaration that extends a sealed interface?
Interfaces cannot be declared final (they're implicitly abstract)
362
Which modifier combination in this interface declaration would cause a compile error when extending a sealed interface?
private is not allowed (interfaces cannot be private)
363
What three modifiers must a subclass of a sealed class declare exactly one of?
final, sealed, or non-sealed
364
True or False: When extending a sealed type, you can combine access modifiers like public with the required sealed/final/non-sealed modifier.
False (no other access modifiers are allowed when extending sealed types)
365
Why can't interfaces be declared final in Java?
Because interfaces are implicitly abstract by nature
366
What is wrong with the following sealed class declaration, and how would you fix it?
The error is in the permits clause - it must use the fully qualified name for nested classes. Correct version: java public sealed class Computer permits Computer.Laptop { final class Laptop extends Computer {} }
367
Why does Java require Computer.Laptop instead of just Laptop in the permits clause when permitting a nested class?
Java requires fully qualified names (OuterClass.NestedClass) in permits clauses to explicitly specify the nested class's scope and avoid ambiguity with potential top-level classes of the same name.
368
What compilation error would occur if you wrote permits Laptop instead of permits Computer.Laptop for a nested class in a sealed hierarchy?
The compiler would fail with an error like "Laptop is not accessible in this context" or "invalid permitted subclass" because it cannot resolve the unqualified nested class name.
369
In the corrected version below, why is Laptop declared as final?
Because all permitted subclasses of a sealed class must be either final, sealed, or non-sealed - this is a Java language requirement for sealed class hierarchies.
370
What would happen if you omitted the permits Computer.Laptop clause entirely in this example?
The code would fail to compile because a sealed class must explicitly declare all its permitted subclasses using the permits clause.
371
Given the following sealed class hierarchy, why does the area method fail to compile?
The area method fails to compile because the switch expression does not cover all permitted subtypes of Shape (Square is missing). A default case or explicit handling of Square is required.
372
What are the two ways to fix the compilation error in the area method for the sealed Shape hierarchy?
Either: Add a case for Square: java case Square sq -> sq.sideLength() * sq.sideLength(); Add a default case (though this is less precise for sealed hierarchies).
373
Why does the following interface declaration cause a compilation error?
The error occurs because interfaces cannot be declared final—they are implicitly abstract and designed for extension.
374
What is wrong with this interface declaration?
The static modifier is not allowed in interface declarations, resulting in a compilation error.
375
What are the only two permitted modifiers for interfaces extending a sealed interface?
The permitted modifiers are sealed or non-sealed. Interfaces cannot be final or static.
376
What is the correct syntax for declaring a sealed class Animal that permits subclasses Dog and Cat?
java public sealed class Animal permits Dog, Cat { // ... }
377
Identify two errors in this sealed class declaration: public class sealed Animal {}
Wrong modifier order (sealed must come before class) Missing permits clause (unless subclasses are in same file)
378
What are the three valid modifiers for a subclass of a sealed class?
final, sealed, or non-sealed
379
Why does this code fail compilation?
The permitted subclass Mammal is in a different package than the sealed class Animal, which requires module access.
380
What is wrong with this interface declaration as a subclass of a sealed type?
Interfaces cannot be declared final when extending sealed types - they can only be sealed or non-sealed.
381
Which modifier is invalid for a sealed class subclass that's an interface?
final (interfaces can't be final)
382
What happens if you declare a sealed class without a permits clause and without any subclasses in the same file?
It won't compile - a sealed class must explicitly declare its permitted subclasses either through permits or by having them in the same file.
383
In which two cases can a sealed class omit the permits clause?
1. When all permitted subclasses are declared in the same file 2. When the sealed class is nested and subclasses are declared in the same enclosing class
384
What is the purpose of the sealed keyword in the PaymentMethod interface declaration, and which classes/interfaces are permitted to implement/extend it?
The sealed keyword restricts which classes can implement it. PaymentMethod permits CreditCard, BankTransfer, and CryptoPayment to implement it. java public sealed interface PaymentMethod permits CreditCard, BankTransfer, CryptoPayment { }
385
Why is BankTransfer declared as a sealed interface and what are its permitted subtypes?
BankTransfer is sealed to control extension, permitting only ACHTransfer and WireTransfer: java public sealed interface BankTransfer extends PaymentMethod permits ACHTransfer, WireTransfer {}
386
What makes CryptoPayment different from other implementations of PaymentMethod in terms of extensibility?
CryptoPayment is declared non-sealed, allowing unrestricted subclassing: java public non-sealed class CryptoPayment implements PaymentMethod {}
387
What two methods must all implementations of PaymentMethod provide, according to the interface?
getAmount() and process(): java BigDecimal getAmount(); void process();
388
In the Crane record example, how does the compact constructor differ from a traditional constructor, and what validation does it perform?
The compact constructor omits parameters and assignments, validating that numberEggs isn’t negative: java public Crane { if (numberEggs < 0) throw new IllegalArgumentException(); }
389
What methods are auto-generated for a record like Crane, and which fields do they use?
Records auto-generate equals(), hashCode(), toString(), and getters for all fields (numberEggs, name).
390
How would you rewrite this traditional class as a record while preserving the validation?
As a record with compact constructor: java public record Crane(int numberEggs, String name) { public Crane { if (numberEggs < 0) throw new IllegalArgumentException(); } }
391
What keyword combination ensures that WireTransfer cannot be subclassed further?
final class WireTransfer: java public final class WireTransfer implements BankTransfer {}
392
What are the four auto-generated components in a Java record?
Constructor, getters (e.g., name() instead of getName()), equals() & hashCode(), and toString().
393
Why does this line fail to compile?
Records are immutable - no setter is auto-generated. You can't modify numberEggs() after construction.
394
How can you add validation to a record's constructor? Show the correct syntax.
Use a compact constructor: java public record BankAccount(String id, BigDecimal balance) { public BankAccount { if (balance.compareTo(BigDecimal.ZERO) < 0) { throw new IllegalArgumentException("Negative balance"); } } }
395
What two inheritance-related restrictions apply to records? Provide code examples that would fail.
1) Cannot extend classes: java public record Student(String id) extends Person {} // ERROR Cannot be abstract: java public abstract record Task(String description); // ERROR
396
Identify two customization limitations of records.
1) Can't add instance fields outside the header. 2) Can't override accessors to make them non-public.
397
In the sealed hierarchy example, which records directly implement the Shape interface?
Circle and Rectangle directly implement Shape, while Triangle and Quadrilateral implement Polygon which extends Shape.
398
What's wrong with this record declaration?
Records cannot declare instance fields outside the header. The age field declaration is invalid.
399
In the Shape sealed hierarchy, what mathematical operation makes Quadrilateral's area calculation unique compared to the other shapes?
It uses Math.sin(angle) in its area calculation: java return side1 * side2 * Math.sin(angle);