Loading
Java Modifier-interview

Q1. What is the difference between public, private, protected, and default in Java?
  • public Accessible everywhere.
  • private Accessible only within the same class.
  • protected Accessible within the same package and by subclasses (even in different packages).
  • default (no modifier) Accessible only within the same package.






Q2. Can a top-level class be private or protected in Java?

No.

  • Top-level classes can only be public or default.
  • private and protected are allowed only for nested (inner) classes.





Q3. What happens if two classes in different packages try to access a default method or variable?

They cannot access it because default (package-private) members are visible only within the same package.






Q4. Can constructors use access modifiers? If yes, what’s the effect?

 Yes.

  • private constructor Prevents object creation outside the class (Singleton).
  • protected constructor Can be used by subclasses or classes in the same package.
  • public constructor Anyone can create objects.
  • default constructor Accessible within the same package.





Q5. Can a class or method be declared as both final and abstract? Why/Why not?

 No.

  • final Cannot be inherited/overridden.
  • abstract Must be inherited/overridden.
    They are contradictory.