Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
Chaturmind
← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: Fresher to 2 YearsObject-Oriented Programming
✓ FreeBeginner· 7 min read

Classes, Objects, Packages & Access Modifiers — Interview Questions

OOP in one minute, classes vs objects, every way to create an object, the Object class methods, packages, access modifiers and why getters/setters beat public fields.

Published September 25, 2026


How to use this lesson

This chapter's questions test whether you can explain OOP in plain language and back it up with code. Keep definitions short and follow each one with a real example: a BankAccount, an Order, an Employee. It sounds far more convincing than textbook phrasing.

Q1. Explain object-oriented programming in Java.

Short answer: OOP organises a program around objects, which bundle data (fields) with the behaviour that operates on it (methods). Java builds on four principles:

  • Encapsulation: hide state and expose behaviour.
  • Inheritance: reuse and extend a parent type.
  • Polymorphism: one interface, many implementations.
  • Abstraction: expose what an object does, not how it does it.
public class BankAccount {                 // class = blueprint
    private long balancePaise;             // encapsulated state

    public void deposit(long amountPaise) {          // behaviour guards the state
        if (amountPaise <= 0) throw new IllegalArgumentException("amount must be positive");
        balancePaise += amountPaise;
    }
    public long balance() { return balancePaise; }
}
BankAccount acc = new BankAccount();       // object = one instance with its own state

Key points to cover:

  • The payoff is maintainability. Changes stay local, types model the business domain, and new behaviour can be added through new classes.

Learn it in depth → Classes and Objects

Q2. What are classes and objects?

Short answer: A class is a blueprint that defines state (fields) and behaviour (methods). An object is a concrete instance of that class, created at runtime with its own copy of the instance fields.

Key points to cover:

  • One class, many objects: new Employee("Asha") and new Employee("Ravi") share the code but have different state.
  • A class can also have static members that belong to the class itself, not to any object.
  • Objects live on the heap. Variables hold references to them.

Learn it in depth → Classes and Objects

Q3. What are the different ways to create an object in Java?

Short answer:

  1. The new keyword.
  2. Reflection, with Constructor.newInstance().
  3. clone().
  4. Deserialization.
  5. Factory or builder methods, which use one of the above internally.
Employee e1 = new Employee("Asha");                                         // 1. new
Employee e2 = Employee.class.getDeclaredConstructor(String.class)
                            .newInstance("Ravi");                           // 2. reflection
Employee e3 = e1.clone();                        // 3. clone (needs Cloneable + an overridden clone())
Employee e4 = (Employee) objectInputStream.readObject();                    // 4. deserialization
List<String> names = List.of("a", "b");                                     // 5. static factory

Key points to cover:

  • Reflection is how frameworks such as Spring and Hibernate create your beans and entities.
  • Class.newInstance() is deprecated. Use getDeclaredConstructor().newInstance().
  • clone() and deserialization don't run the constructor, so invariants that constructors enforce can be bypassed. That's a known security and correctness risk.

Q4. Can a class have no fields or methods?

Short answer: Yes. An empty class is legal: class Marker {}. It still inherits everything from Object (toString, equals, hashCode, …), and you can create instances of it.

Key points to cover:

  • Real uses:
    • Marker interfaces such as Serializable (empty interfaces rather than classes).
    • Placeholder types in generics.
    • Custom exception classes that add nothing but a type name, such as class InsufficientFundsException extends RuntimeException {}.

Q5. What methods does the Object class provide?

Short answer: equals(), hashCode(), toString(), getClass(), clone(), wait(), notify(), notifyAll(), and the deprecated finalize().

Key points to cover:

MethodPurposeOverride?
equals(Object)Logical equality (defaults to ==)Yes, for value-like classes
hashCode()Hash for HashMap/HashSet; must agree with equalsAlways together with equals
toString()Readable text for logs and debuggingAlmost always
getClass()Runtime classCan't (it's final)
clone()Field-by-field copy (protected, needs Cloneable)Rarely; prefer copy constructors
wait/notify/notifyAllLow-level thread coordination on a monitorCan't (they're final)
finalize()Deprecated cleanup hookNever
  • Records generate equals, hashCode and toString for you.

Learn it in depth → equals() and hashCode()

Q6. What is a package in Java?

Short answer: A package is a namespace that groups related classes and interfaces, such as java.util or com.shop.orders. It maps to a folder structure on disk.

Key points to cover:

  • It's declared with package com.shop.orders; as the first statement in a file. Classes in other packages are used through import.
  • The convention is reverse domain names (com.company.product.module), which keeps names unique worldwide.
  • There are built-in packages (java.lang is imported automatically) and user-defined ones.

Q7. Why do we use packages?

Short answer: To organise code, avoid naming conflicts, and control access.

Key points to cover:

  • Organisation: related classes live together (for example …orders.api, …orders.domain, …orders.persistence).
  • No name clashes: java.util.Date and java.sql.Date can both exist.
  • Access control: package-private (default) members are visible only inside the package, which lets you hide implementation classes.
  • Modularity: packages are the unit that Java modules (module-info.java) export or hide.

Q8. What are the access modifiers in Java?

Short answer: Four levels, from most to least open: public, protected, default (package-private, meaning no keyword), and private.

ModifierSame classSame packageSubclass (other package)Everywhere
public✅✅✅✅
protected✅✅✅ (through inheritance)❌
default✅✅❌❌
private✅❌❌❌

Learn it in depth → Classes and Objects

Q9. When would you use each access modifier? And why use getters and setters instead of public fields?

Short answer: Start with the most restrictive level that works:

  • private for fields and internal helpers.
  • package-private for classes that only collaborate inside one module.
  • protected for extension points meant for subclasses.
  • public only for the API that other code is meant to use.

Key points to cover:

  • Getters and setters, rather than public fields, let you:
    • validate input (reject a negative price);
    • change the internal representation without breaking callers (store paise instead of rupees);
    • make a field read-only (a getter with no setter);
    • add logging, lazy loading or change notification.
  • Better still, don't generate a setter for every field automatically. Expose behaviour instead: account.deposit(x) rather than setBalance(). For pure data carriers, use an immutable record.
public void setPrice(BigDecimal price) {
    if (price.signum() < 0) throw new IllegalArgumentException("price cannot be negative");
    this.price = price;
}

Common trap: saying "getters and setters are encapsulation". A public setter for every field exposes the state just as much as a public field does. Encapsulation means protecting invariants.

Q10. Can a top-level class be private or protected?

Short answer: No. A top-level class can only be public or package-private. private and protected only make sense relative to an enclosing class, so they're allowed on nested classes.

public class Outer {
    private static class Helper { }     // fine: nested
    protected class Inner { }           // fine: nested
}
// private class Top { }                // compile error: modifier private not allowed here

Key points to cover:

  • A .java file can have at most one public top-level class, and it must match the file name.

Follow-up questions this topic invites — and their answers

Q: Is protected more or less restrictive than default access? A: Less restrictive. protected includes everything default access allows (same package), and adds subclasses in other packages.

Q: What's the difference between import and a static import? A: import lets you use a class by its simple name. import static lets you use a class's static members directly, for example import static java.lang.Math.max; and then max(a, b). Use static imports sparingly, because they can hide where a method comes from.

Q: How are Java modules different from packages? A: A package groups classes. A module (Java 9+) groups packages, and declares which of them it exports and which modules it requires. That gives you strong encapsulation: even public classes in non-exported packages can't be used from outside the module.

Q: Why prefer a copy constructor over clone()? A: clone() has an awkward contract: the Cloneable marker, a protected method, shallow copies by default, and no constructor call. A copy constructor or a static factory (new Order(other), Order.copyOf(other)) is explicit, type safe, and easy to make a deep copy.

Previous

Data Types, Wrapper Classes & Equality — Interview Questions

Next

Inheritance, Composition, this & super — Interview Questions

AI Tutor

Lesson: Classes, Objects, Packages & Access Modifiers — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.