Java Object Oriented Programming Interview Questions
Introduction#
Object-Oriented Programming (OOP) is the backbone of Java, enabling developers to build modular, scalable, and maintainable applications. For Java learners and job seekers, mastering OOP concepts is critical, as they form the foundation of most technical interviews. This blog post, part of the "Java Programming Handbook," dives deep into Java OOP interview questions, offering in-depth answers and realistic code examples. Whether you're preparing for a junior developer role or aiming to solidify your Java skills, these carefully curated questions will help you understand Java OOP concepts like inheritance, polymorphism, and encapsulation. Expect clear explanations, practical insights, and tips to ace your next Java interview. Let’s get started with the core topics and questions that interviewers love to ask!
Four Pillars of OOP#
1. What are the four pillars of OOP in Java?#
The four pillars of OOP are Encapsulation, Inheritance, Polymorphism, and Abstraction. Encapsulation bundles data and methods, protecting data via access modifiers. Inheritance allows a class to inherit properties from another, promoting code reuse. Polymorphism enables one interface to represent different types, achieved through method overloading or overriding. Abstraction hides complex implementation details, exposing only necessary features via abstract classes or interfaces. These pillars make Java code modular and maintainable.
Code Example:
Output:
Note: Interviewers ask this to gauge your foundational understanding. Relate each pillar to a real-world scenario, like a car (encapsulation: private engine; inheritance: car extends vehicle).
2. How does abstraction differ from encapsulation?#
Abstraction and encapsulation are distinct but complementary. Abstraction focuses on hiding implementation details, showing only essential features (e.g., using abstract classes or interfaces). Encapsulation protects data by bundling it with methods and restricting access via modifiers like private
. Abstraction is about design simplicity, while encapsulation ensures data security.
Code Example:
Output:
Note: Clarify the distinction in interviews to show depth. Think of abstraction as a TV remote (only buttons visible) and encapsulation as a locked safe (data secured).
3. Why is polymorphism important in Java?#
Polymorphism means "many forms." In Java, it allows one object to behave in different ways based on the context.
It helps to:
- Write flexible code that works with different types of objects.
- Reuse code — you don’t need to write the same logic multiple times.
- Easily extend your program without changing existing code much.
Types of Polymorphism in Java
Type | What it means |
---|---|
1. Compile-time (Method Overloading) | Same method name but different parameters (done in the same class). |
2. Runtime (Method Overriding) | Subclass changes behavior of a method defined in its superclass. |
Code Example:
Here:
- The variable is of type
Animal
, but the object isDog
orCat
. - Java decides at runtime which
sound()
method to call — this is runtime polymorphism.
Output:
Java Classes and Objects#
4. What is a class in Java?#
A class is a blueprint for creating objects, defining properties (fields) and behaviors (methods). It encapsulates data and functionality, serving as a template. Objects are instances of a class, created using the new
keyword. Classes support OOP principles like inheritance and polymorphism.
Code Example:
Output:
Note: This is a beginner question to test core OOP understanding. Think of a class as a recipe and objects as dishes made from it.
5. How is memory allocated for objects in Java?#
In Java, objects are created in the heap memory using the new
keyword. The reference variable (stored in stack memory) points to the object’s address in the heap. Instance variables are stored within the object, and methods are stored in the method area (shared across objects). Garbage collection reclaims memory when objects are no longer referenced.
Code Example:
Output:
Note: Interviewers ask this to check memory management knowledge. Explain heap vs. stack clearly.
Java Constructor#
6. What is a constructor in Java?#
A constructor is a special method used to initialize objects. It has the same name as the class, no return type, and is called automatically when an object is created with new
. Constructors can be default (no parameters) or parameterized. They initialize instance variables and set up the object’s state.
Code Example:
Output:
Note: Emphasize constructor’s role in object initialization. Compare it to setting up a new phone with initial settings.
7. Can a constructor be overloaded?#
Yes, constructors can be overloaded by defining multiple constructors with different parameter lists. This allows flexibility in object creation. Overloaded constructors must differ in the number, type, or order of parameters. Java selects the appropriate constructor based on the arguments provided.
Code Example:
Output:
Note: This tests understanding of constructor flexibility. Mention real-world use, like different ways to configure a product.
Encapsulation in Java#
8. What is encapsulation and how it is achieved?#
Encapsulation means wrapping or hiding the internal details (data) of a class and only exposing what’s necessary through methods.
Think of it like a capsule — it holds the medicine inside and only lets you take it in a controlled way.
Code Example:
Output:
In the BankAccount
class:
- The
balance
field is private, so it can’t be accessed or modified directly from outside the class. - Only the setter method (
setBalance
) can change the balance, and it has a check to allow only non-negative values.
So, even if someone tries to set a negative balance, the method blocks it — this protects your data from being corrupted.
9. Why use getters and setters instead of public fields?#
Getters and setters provide controlled access to private fields, enabling validation, logging, or additional logic. Public fields allow unrestricted access, risking data corruption. Getters/setters enforce encapsulation, making code maintainable and secure.
Code Example:
Output:
Inheritance in Java and Constructors in Inheritance#
10. What is inheritance in Java?#
Inheritance allows a class (subclass) to inherit fields and methods from another class (superclass), promoting code reuse. Use the extends
keyword. Subclasses can add new methods or override inherited ones. Java supports single inheritance for classes.
Code Example:
Output:
Note: Explain code reuse benefits. Compare to inheriting family traits.
11. How are constructors handled in inheritance?#
In inheritance, a subclass constructor implicitly calls the superclass’s no-arg constructor using super()
. If the superclass lacks a no-arg constructor, you must explicitly call a parameterized constructor using super(args)
. Constructors are not inherited but can be chained.
Code Example:
Output:
Note: Clarify super()
usage. Think of it as setting up the parent before the child.
this vs super keyword#
12. What is the difference between this
and super
?#
The this
keyword refers to the current object, used to access instance variables or methods of the same class. The super
keyword refers to the immediate superclass, used to call superclass constructors, methods, or access fields. Both resolve ambiguity and enable proper scoping.
Code Example:
Output:
Note: Use this
and super
to clarify scope in interviews. Compare to pointing at yourself (this
) vs. your parent (super
).
13. Can we access parent class fields and methods using super
in Java?#
Yes, in Java, the super
keyword is used to access fields and methods of the parent class (also called the superclass) from a child class.
You can use:
super.fieldName
→ to access a parent class variable.super.methodName()
→ to call a parent class method.super(...)
→ to call the parent class constructor (must be the first line in the child constructor).
Code Example:
Output:
Method Overriding in Java#
14. What is method overriding?#
Method overriding means that a subclass provides its own version of a method that is already defined in its parent class.
- The method in the subclass must have the same name, return type, and parameters.
- It’s used to change or extend the behavior of the parent method.
- It enables runtime polymorphism, meaning the method that gets called depends on the actual object, not the reference type.
Code Example:
Output:
15. Can a private method be overridden?#
No, private
methods cannot be overridden because they are not inherited by subclasses.
They are only accessible within the class where they are defined.
Even if a subclass declares a method with the same name and parameters, it’s not overriding — it’s simply defining a completely new method (method hiding, not overriding).
This is because private methods use static binding (decided at compile time), not dynamic binding (decided at runtime like overridden methods).
Code Example:
Output:
If you try to call show()
using a Parent
reference, it won’t even compile because Parent.show()
is private and invisible outside the class.
Dynamic Method Dispatch#
16. What is dynamic method dispatch?#
Dynamic Method Dispatch is the process by which Java decides at runtime which version of an overridden method to execute, based on the actual object type, not the reference type.
It’s a core concept behind runtime polymorphism, where:
- The reference variable is of the parent class type.
- But the actual object (created with
new
) is of a child class. - When a method is called on that reference, Java looks at the object type, not the reference type, to decide which method to run.
Code Example:
Output:
- At compile time, Java sees
animal.sound()
and looks inAnimal
class. - But at runtime, Java notices that
animal
is actually pointing to aDog
object. - So, it executes
Dog
's version ofsound()
— this is dynamic dispatch.
17. How does dynamic method dispatch work with interfaces?#
Dynamic Method Dispatch with interfaces means that Java determines at runtime which method implementation to execute — based on the actual object type, even though you're using an interface reference.
- An interface defines a contract (method signatures only).
- Any class that implements the interface provides its own version of the methods.
- When you assign an implementing class object to an interface reference, Java dynamically binds the method call at runtime to the actual method in the object’s class.
👉 This is runtime polymorphism in action using interfaces.
Code Example:
Output:
- The reference type is
Flyable
(interface). - The object type is either
Bird
orAirplane
(implementing class). - Even though we use the same interface reference
flyer
, Java decides at runtime which method to call — based on the object assigned.
Polymorphism using Overloading and Overriding in Java#
18. What is the difference between overloading and overriding?#
Overloading occurs when multiple methods in the same class have the same name but different parameters (compile-time polymorphism). Overriding occurs when a subclass redefines a superclass method with the same signature (runtime polymorphism). Overloading is resolved at compile time; overriding at runtime.
Feature | Overloading | Overriding |
---|---|---|
Where? | Same class | Between superclass and subclass |
Signature? | Same method name, different parameters | Same method name, same parameters |
Return Type? | Can be different | Must be same or covariant |
When Resolved? | Compile time (early binding) | Runtime (dynamic method dispatch) |
Purpose | Code flexibility with multiple versions | Modify or extend behavior from superclass |
Type of Polymorphism | Compile-time polymorphism | Runtime polymorphism |
Code Example:
Output:
calc.add(5, 3)
calls the overridden version inAdvancedCalc
, decided at runtime.calc.add(5.5, 3.3)
uses method overloading, chosen at compile time based on parameters.
19. Can overloaded methods have different return types?#
Yes, overloaded methods can have different return types, as long as their parameter lists differ (number, type, or order). The return type alone cannot distinguish overloaded methods, but it can vary if the method signatures are unique.
Code Example:
Output:
Abstract Classes in Java#
20. What is an abstract class in Java?#
An abstract class is a class declared with the abstract
keyword, which cannot be instantiated and may contain abstract methods (without implementation) and concrete methods. It’s used to define a common structure for subclasses, enforcing method implementation while providing shared functionality.
Code Example:
Output:
21. Can an abstract class have a constructor?#
Yes, an abstract class can have constructors to initialize fields or set up shared state. These constructors are called by subclass constructors (via super()
). Since abstract classes cannot be instantiated directly, their constructors are only invoked during subclass object creation.
Code Example:
Output:
Interfaces in Java#
22. What is an interface in Java?#
An interface is a blueprint for classes, declared with the interface
keyword, containing abstract methods, default methods, and constants. Classes implement interfaces using implements
, providing concrete implementations for all abstract methods. Interfaces enable multiple inheritance and abstraction.
Code Example:
Output:
23. Can an interface have instance variables?#
No, interfaces cannot have instance variables. They can only have public static final
fields (constants). This ensures interfaces remain stateless, focusing on defining behavior rather than storing data, unlike abstract classes.
Code Example:
Output:
24. What are default methods in interfaces?#
Default methods, introduced in Java 8, are methods in interfaces with a default implementation, declared with the default
keyword. They allow interfaces to evolve without breaking existing implementations. Classes can override default methods or use them as-is.
Code Example:
Output:
25. What is the difference between an abstract class and an interface?#
An abstract class can have both abstract and concrete methods, instance variables, and single inheritance. An interface primarily has abstract methods (and default/static methods since Java 8), constants, and supports multiple inheritance.
Feature | Abstract Class | Interface |
---|---|---|
Methods | Can have abstract and concrete methods | All methods are abstract by default (till Java 7); from Java 8+, can include default and static methods |
Variables | Can have instance variables (state) | Only constants (public static final fields) |
Constructors | Can have constructors | Cannot have constructors |
Inheritance | Single inheritance only | Multiple inheritance through interfaces |
Usage | Used for code reusability with partial abstraction | Used to define a contract for behavior |
Access Modifiers | Can have any access modifiers | Methods are implicitly public abstract |
When to Use What?
- Use an abstract class when you want to:
- Share state (fields/variables) across subclasses
- Provide default behavior + mandatory behavior
- Maintain some implementation details
- Use an interface when you want to:
- Define a pure contract without shared state
- Allow multiple classes to implement the same behavior
- Enable multiple inheritance of types
Code Example:
Output:
Conclusion#
Mastering Java OOP concepts is essential for excelling in technical interviews and building robust applications. From understanding the four pillars to tackling interfaces and polymorphism, these 25 Java OOP interview questions provide a solid foundation for Java learners and job seekers. Practice these questions, experiment with the code examples, and explore edge cases to deepen your understanding. OOP is like constructing a well-designed building—each concept interlocks to create a strong structure. Keep coding, stay curious, and check out other chapters in the Java Programming Handbook to continue your journey toward Java interview success!