Understand the idea. Compare it. Explain it. Test yourself.
Question 11 of 12
Can a top-level class be private?
Solution and explanation
Answer
No. A top-level class (one not nested inside another class) can only be public or package-private (no modifier). private and protected give a compile error:
private class Helper { } // error: modifier private not allowed here
Why
private means "visible only inside the enclosing class". A top-level class has no enclosing class, so private would make it usable by nobody, which is meaningless. protected relates to subclasses of an enclosing class, which also does not apply.
What you can do instead
// Payment.java
public class Payment {
private static class Validator { } // nested classes CAN be private
}
class InternalHelper { } // package-private: visible only inside the same package
Modifier
Top-level class
Nested class
public
Yes
Yes
(default) package-private
Yes
Yes
protected
No
Yes
private
No
Yes
Practice explaining thisQuestion 12 of 12
What is an abstract class?
Solution and explanation
What it is
An abstract class is a class declared with abstract that cannot be instantiated. It is meant to be extended. It can contain abstract methods (no body) that subclasses must implement, as well as normal methods, fields and constructors shared by all subclasses.
Example
public abstract class Payment {
protected final double amount;
protected Payment(double amount) { this.amount = amount; }
public abstract boolean pay(); // each payment type implements this
public void printReceipt() { // shared, concrete behaviour
System.out.println("Paid ₹" + amount + " via " + getClass().getSimpleName());
}
}
public class UpiPayment extends Payment {
private final String upiId;
public UpiPayment(double amount, String upiId) { super(amount); this.upiId = upiId; }
@Override public boolean pay() {
System.out.println("Collect request sent to " + upiId);
return true;
}
}
Payment p = new UpiPayment(499, "ravi@okicici");
if (p.pay()) p.printReceipt();
// new Payment(100); // compile error: Payment is abstract
Rules
A class with at least one abstract method must be declared abstract.
An abstract class may have zero abstract methods (just to prevent instantiation).
It can have constructors (called through super() from subclasses), static methods, final methods and any fields.
A concrete subclass must implement all inherited abstract methods, or itself be abstract.
abstract cannot be combined with final, private or static on a method.
When to use
Use an abstract class when related classes share state and code (a template), for example the Template Method pattern: the abstract class defines the algorithm steps and subclasses fill in specific steps. Use an interface when unrelated classes only need to share a capability.