Java Notes
35+ Object-Oriented Programming interview questions with detailed answers covering inheritance, polymorphism, abstraction, encapsulation, and design patterns.
1. What are the four pillars of OOP?
| Pillar | Definition | Java Implementation |
|---|---|---|
| Encapsulation | Bundling data + methods; hiding internals | Private fields + public getters/setters |
| Inheritance | Acquiring properties from parent class | extends keyword |
| Polymorphism | Same interface, different implementations | Method overriding, method overloading |
| Abstraction | Hiding complexity, showing essentials | Abstract classes, interfaces |
3. What is inheritance? What are its types?
Inheritance allows a class to acquire properties and behaviors of another class.
| Type | Java Support | Example |
|---|---|---|
| Single | ✅ | Class B extends A |
| Multilevel | ✅ | C extends B, B extends A |
| Hierarchical | ✅ | B extends A, C extends A |
| Multiple (class) | ❌ | Not supported (use interfaces) |
| Hybrid | ❌ (partial via interfaces) | Combination of above |
class Animal { void eat() { } }
class Dog extends Animal { void bark() { } } // Single
class Puppy extends Dog { void play() { } } // Multilevel
class Cat extends Animal { void meow() { } } // Hierarchical4. Why doesn't Java support multiple inheritance with classes?
Diamond Problem: If class C extends both A and B, and both have method display(), which version does C inherit?
Java avoids this ambiguity. With interfaces (Java 8+ default methods), you must explicitly override:
interface A { default void show() { System.out.println("A"); } }
interface B { default void show() { System.out.println("B"); } }
class C implements A, B {
public void show() { A.super.show(); } // Must resolve conflict
}5. What is polymorphism? Explain both types.
Compile-time (Static) Polymorphism — Method Overloading:
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}Runtime (Dynamic) Polymorphism — Method Overriding:
class Shape {
double area() { return 0; }
}
class Circle extends Shape {
double radius;
double area() { return Math.PI * radius * radius; } // Overridden
}
class Rectangle extends Shape {
double width, height;
double area() { return width * height; } // Overridden
}
// Polymorphic behavior
Shape s = new Circle(); // Parent reference, child object
s.area(); // Calls Circle's area() — decided at RUNTIME6. What is abstraction?
Abstraction hides implementation details and shows only functionality:
// Abstract class
abstract class Vehicle {
abstract void start(); // WHAT to do (no HOW)
void stop() { // Can have concrete methods too
System.out.println("Vehicle stopped");
}
}
class Car extends Vehicle {
void start() { // HOW to do it
System.out.println("Turn key, press start button");
}
}
class ElectricCar extends Vehicle {
void start() {
System.out.println("Press power button, silent start");
}
}7. Abstract class vs Interface — when to use which?
| Use Abstract Class When | Use Interface When |
|---|---|
| Classes share common state (fields) | Defining a contract/capability |
| Need constructors | Multiple inheritance needed |
| Close relationship (IS-A) | Unrelated classes share behavior |
| Want to provide base implementation | Want pure abstraction |
Example: Animal (abstract class) vs Flyable (interface) — A Bird IS-A Animal and CAN Flyable.
8. Can we create object of abstract class?
No. But you can:
- Create reference of abstract class pointing to child object
- Use anonymous inner class
abstract class Animal { abstract void sound(); }
// ❌ Animal a = new Animal(); // Compile error
// ✅ Reference to child
Animal a = new Dog();
// ✅ Anonymous class
Animal b = new Animal() {
void sound() { System.out.println("Anonymous sound"); }
};9. What is constructor chaining?
Calling one constructor from another:
class Student {
String name;
int age;
String course;
Student() {
this("Unknown", 18, "Java"); // Calls 3-arg constructor
}
Student(String name) {
this(name, 18, "Java");
}
Student(String name, int age, String course) {
this.name = name;
this.age = age;
this.course = course;
}
}10. What is method hiding vs overriding?
class Parent {
static void staticMethod() { System.out.println("Parent static"); }
void instanceMethod() { System.out.println("Parent instance"); }
}
class Child extends Parent {
static void staticMethod() { System.out.println("Child static"); } // HIDING
void instanceMethod() { System.out.println("Child instance"); } // OVERRIDING
}
Parent ref = new Child();
ref.staticMethod(); // "Parent static" — hiding (compile-time)
ref.instanceMethod(); // "Child instance" — overriding (runtime)11. What is an Object class? List its methods.
java.lang.Object is the root of all Java classes.
| Method | Purpose |
|---|---|
toString() | String representation |
equals(Object) | Logical equality |
hashCode() | Hash code for collections |
getClass() | Runtime class info |
clone() | Create copy |
finalize() | Pre-GC cleanup (deprecated) |
wait(), notify(), notifyAll() | Thread synchronization |
12. Why override both equals() and hashCode()?
Contract: If two objects are equal (equals() returns true), they MUST have the same hashCode().
If you override equals() without hashCode(), HashMap/HashSet won't work correctly.
13. What is the difference between shallow copy and deep copy?
// Shallow copy — copies references (not objects)
class Address { String city; }
class Person implements Cloneable {
String name;
Address address;
// Shallow clone — address points to SAME object
Person shallowClone() throws CloneNotSupportedException {
return (Person) super.clone();
}
// Deep clone — creates new Address object too
Person deepClone() throws CloneNotSupportedException {
Person clone = (Person) super.clone();
clone.address = new Address();
clone.address.city = this.address.city;
return clone;
}
}14. What is an inner class? What are its types?
| Type | Defined | Access to Outer |
|---|---|---|
| Member inner class | Inside class, outside method | Yes (including private) |
| Static nested class | With static keyword | Only static members |
| Local inner class | Inside a method | Enclosing method's final vars |
| Anonymous inner class | Inline, no name | Enclosing scope's final vars |
15. What is composition vs inheritance?
| Composition (HAS-A) | Inheritance (IS-A) |
|---|---|
class Car { Engine engine; } | class Dog extends Animal |
| Flexible, loose coupling | Rigid, tight coupling |
| Can change at runtime | Fixed at compile time |
| Preferred in most cases | Use only for true IS-A |
"Favor composition over inheritance" — Gang of Four
16-35. Additional Questions (Brief Answers)
16. What is an association? Relationship between two classes (one-to-one, one-to-many, many-to-many).
17. What is aggregation? Weak HAS-A relationship. Child can exist without parent. Department has Students.
18. What is composition (not the pattern)? Strong HAS-A. Child cannot exist without parent. House has Rooms.
19. Can a class be both abstract and final? No. Abstract requires subclassing; final prevents it.
20. What is upcasting and downcasting?
- Upcasting: Child → Parent reference (implicit, always safe)
- Downcasting: Parent → Child reference (explicit, needs instanceof check)
21. What is the instanceof operator? Checks if object is instance of a class/interface.
22. What is a POJO? Plain Old Java Object — no framework dependencies, just fields + getters/setters.
23. What is a JavaBean? POJO with: no-arg constructor, private fields, public getters/setters, implements Serializable.
24. What is the Liskov Substitution Principle? Subtypes must be substitutable for their base types without breaking the program.
25. What is method dispatch? The mechanism JVM uses to determine which overridden method to call at runtime.
26. Can we override private methods? No. Private methods are not inherited.
27. Can we override final methods? No. Final methods cannot be overridden.
28. What is early binding vs late binding? Early = compile-time (overloading, static); Late = runtime (overriding, virtual methods).
29. What is the SOLID principle? S-Single Responsibility, O-Open/Closed, L-Liskov Substitution, I-Interface Segregation, D-Dependency Inversion.
30. Can an interface extend another interface? Yes, and it can extend multiple interfaces.
31. What are sealed classes (Java 17)? Classes that restrict which other classes can extend them.
32. What is a record (Java 16)? Immutable data carrier class with auto-generated constructor, getters, equals, hashCode, toString.
33. What is an immutable class? Class whose state cannot change after creation (final class, final fields, no setters, deep copy in constructor).
34. What is the template method pattern? Abstract class defines algorithm skeleton; subclasses override specific steps.
35. What is the strategy pattern? Define family of algorithms, encapsulate each, make them interchangeable via interface.
16. Composition vs Inheritance - when to use which?
Answer: Inheritance (IS-A): Dog IS-A Animal. Composition (HAS-A): Car HAS-A Engine. Prefer composition over inheritance — more flexible, avoids tight coupling, easier testing. Use inheritance only when a true IS-A relationship exists.
// Composition (preferred)
class Car {
private Engine engine; // HAS-A
Car(Engine engine) { this.engine = engine; }
}
// Inheritance (use carefully)
class Dog extends Animal { } // IS-A17. Explain the SOLID Principles.
Answer:
- S - Single Responsibility: A class should have only one reason to change
- O - Open/Closed: Open for extension, closed for modification
- L - Liskov Substitution: A subclass should be usable in place of its parent
- I - Interface Segregation: Do not force clients to implement unnecessary methods
- D - Dependency Inversion: High-level depend on abstractions, not details
18. What is the difference between Shallow Copy and Deep Copy?
Answer: Shallow copy: The object is copied but internal references still point to the same objects. Deep copy: A complete independent copy — nested objects are also copied. The Cloneable interface implements shallow copy by default.
19. What is Covariant Return Type?
Answer: An overriding method can return a more specific (subtype) return type than the parent method. Supported since Java 5.
class Animal { Animal create() { return new Animal(); } }
class Dog extends Animal {
@Override
Dog create() { return new Dog(); } // Covariant - Dog instead of Animal
}20. What are the important methods of the Object class?
Answer: toString() (string representation), equals() (logical equality), hashCode() (hash code), clone() (copy), getClass() (runtime class), finalize() (before GC), wait()/notify() (thread communication).
21. What is the equals() and hashCode() contract?
Answer: If a.equals(b) == true then a.hashCode() == b.hashCode() MUST be true. Either override both or neither. Following this contract is mandatory for HashMap/HashSet to work correctly.
22. What is a Marker Interface?
Answer: An interface that has no methods — it serves only as a marker. Examples: Serializable, Cloneable, Remote. The JVM assigns special behavior to them. In modern Java, annotations are preferred over marker interfaces.
23. What are the types of Inner Class?
Answer:
- Member Inner Class: Defined inside a class, gets a reference to the outer class
- Static Nested Class: Static, does not get a reference to the outer class
- Local Inner Class: Defined inside a method
- Anonymous Inner Class: Unnamed, one-time use (replaced by lambda in modern Java)
24. Method Hiding vs Method Overriding?
Answer: Static methods are hidden (reference type decides), instance methods are overridden (object type decides). Hiding is resolved at compile-time, overriding is resolved at runtime.
25. What is the difference between Association, Aggregation, and Composition?
Answer:
- Association: General relationship (Teacher teaches Student)
- Aggregation: Weak HAS-A (Department has Teachers — teachers exist independently)
- Composition: Strong HAS-A (House has Rooms — rooms can't exist without house)
26. Why Java doesn't support multiple inheritance of classes?
Answer: To avoid the Diamond Problem — if two parent classes define the same method, ambiguity arises. Java achieves multiple inheritance through interfaces (Java 8 default methods handle the limited diamond problem).
27. What is Upcasting vs Downcasting?
Answer: Upcasting: Child to Parent reference (implicit, safe). Downcasting: Parent to Child reference (explicit, ClassCastException possible). Use instanceof check before downcasting.
Animal a = new Dog(); // Upcasting (implicit)
Dog d = (Dog) a; // Downcasting (explicit, safe here)28. Can we override private/static/final methods?
Answer: Private: No (not inherited, not visible). Static: No (hidden, not overridden). Final: No (explicitly prevented). Attempting to override final gives compile error.
29. Abstraction vs Encapsulation?
Answer: Abstraction: Hiding implementation and showing only essential features (abstract class/interface). Encapsulation: Bundling data + methods together and controlling data access (private fields + public getters/setters). Abstraction is at the design level, Encapsulation is at the implementation level.
30. How to create an Immutable Class?
Answer: Rules: class final, all fields private final, no setters, deep copy in constructor for mutable fields, return copies (not references) from getters.
public final class ImmutablePerson {
private final String name;
private final List<String> hobbies;
public ImmutablePerson(String name, List<String> hobbies) {
this.name = name;
this.hobbies = new ArrayList<>(hobbies); // Deep copy
}
public String getName() { return name; }
public List<String> getHobbies() { return Collections.unmodifiableList(hobbies); }
}Summary
In this chapter, we learned about OOPs Interview Questions in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for OOPs Interview Questions.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, interview, questions, oops
Related Java Master Course Topics