OOP & SOLID Junior cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

  1. 1. What is the difference between a class and an object?

    Correct answer: A class is a blueprint, an object is a concrete instance built from it

    A class describes the state and behavior that its instances will have. Each new User() creates a separate object with its own field values.

  2. 2. Which four ideas are usually called the pillars of OOP?

    Correct answer: Encapsulation, abstraction, inheritance, polymorphism

    Encapsulation hides state behind an interface, abstraction models only what matters, inheritance reuses a type, and polymorphism lets one call work with many types.

  3. 3. What does this code print?

    class Counter {
      count = 0;
      increment() {
        this.count++;
      }
    }
    
    const a = new Counter();
    const b = new Counter();
    a.increment();
    a.increment();
    b.increment();
    console.log(a.count, b.count);

    Correct answer: 2 1

    Each instance has its own count field. a was incremented twice and b once, so the counters don't affect each other.

  4. 4. What is a constructor for?

    Correct answer: To initialize a new object and put it into a valid state

    The constructor runs once when the object is created. It sets fields and checks arguments so that the object is usable from the first moment.

  5. 5. Which statement about encapsulation is correct?

    Correct answer: It hides internal state and lets other code change it only through methods

    Encapsulation protects the object's invariants: outside code can't put it into an invalid state because changes go through methods that check the rules.

  6. 6. Why is the balance field better kept private here?

    class Account {
      private balance = 0;
    
      withdraw(amount: number) {
        if (amount > this.balance) throw new Error("Insufficient funds");
        this.balance -= amount;
      }
    }

    Correct answer: So no code can skip the check and make the balance negative

    If balance were public, anyone could write account.balance = -500. A private field forces all changes through withdraw, which guards the invariant.

  7. 7. What is the difference between private in TypeScript and #field in JavaScript?

    Correct answer: private is checked only at compile time, #field is enforced at runtime

    TypeScript erases private during compilation, so (obj as any).secret still works. A #field is a real private element that code outside the class can't read at all.

  8. 8. Who can access a protected member in TypeScript or Java?

    Correct answer: The class itself and its subclasses

    protected is between private and public: subclasses can use the member, but outside code can't. In Java, classes in the same package also have access.

  9. 9. What is abstraction in OOP?

    Correct answer: Showing only what matters for the task and hiding the details

    A PaymentGateway with a charge() method is an abstraction: callers don't need to know about HTTP requests, retries or the provider's API.

  10. 10. What is inheritance?

    Correct answer: A class takes over the fields and methods of another class and can extend them

    With class Admin extends User, Admin gets everything User has and can add or override members. It models an "is-a" relation.

  11. 11. What does this code print?

    class Animal {
      speak() {
        return "...";
      }
    }
    
    class Dog extends Animal {
      speak() {
        return "Woof";
      }
    }
    
    const pet: Animal = new Dog();
    console.log(pet.speak());

    Correct answer: Woof

    The method is chosen by the actual object, not the declared type. The object is a Dog, so its overridden speak() runs. This is runtime polymorphism.

  12. 12. What is polymorphism?

    Correct answer: One interface, many implementations: the same call works with different types

    Code that calls shape.area() works with circles, squares and any future shape. Each type provides its own implementation.

  13. 13. What is the difference between overriding and overloading?

    Correct answer: Overriding replaces a parent method in a subclass, overloading adds methods with the same name and different parameters

    Overriding is resolved at runtime by the object's type. Overloading is resolved at compile time by the argument types, as with print(int) and print(String) in Java.

  14. 14. What does super.method() do inside an overriding method?

    Correct answer: Calls the parent class version of the method

    super lets a subclass extend the parent's behavior instead of fully replacing it, for example by adding logging before calling the original.

  15. 15. Why does this subclass constructor fail?

    class User {
      constructor(public name: string) {}
    }
    
    class Admin extends User {
      constructor(name: string, public level: number) {
        this.level = level;
        super(name);
      }
    }

    Correct answer: this is used before super() is called

    In a derived class, the parent constructor must run first. Until super() returns, this isn't initialized, so touching it throws a ReferenceError.

  16. 16. What is an abstract class?

    Correct answer: A class you can't instantiate directly, meant to be extended

    An abstract class can mix implemented methods with abstract ones that subclasses must provide. new Shape() fails, new Circle() works.

  17. 17. What happens with this code in TypeScript?

    abstract class Shape {
      abstract area(): number;
    }
    
    class Square extends Shape {
      constructor(private side: number) {
        super();
      }
    }

    Correct answer: A compile error: Square must implement area()

    An abstract method has no body. A concrete subclass must implement it, otherwise it has to be declared abstract itself.

  18. 18. What is an interface in OOP?

    Correct answer: A contract that lists methods a type must provide, without implementing them

    An interface such as Comparable or Logger says what an object can do. Classes that implement it decide how.

  19. 19. In Java, how many classes can a class extend and how many interfaces can it implement?

    Correct answer: One class, many interfaces

    Java has single inheritance of implementation to avoid the diamond problem, but a class can implement any number of interfaces.

  20. 20. When is an abstract class a better choice than an interface?

    Correct answer: When related classes share state and code, not just method signatures

    An abstract class can hold fields and implemented methods for a family of close types. An interface fits a capability shared by unrelated types.

  21. 21. Which relation is modeled with inheritance and which with composition?

    Correct answer: "is-a" with inheritance, "has-a" with composition

    A Car is a Vehicle (inheritance), and a Car has an Engine (composition: a field that holds another object).

  22. 22. Which design is better for a car that needs an engine?

    Correct answer: class Car { constructor(private engine: Engine) {} }

    A car isn't a kind of engine, it has one. Composition also lets you pass an electric or a diesel engine without changing the Car class.

  23. 23. What does "favor composition over inheritance" mainly protect against?

    Correct answer: Rigid hierarchies where a change in a parent breaks many subclasses

    Inheritance couples a subclass to its parent's internals. Composition keeps parts behind small interfaces, so you can swap them without touching the hierarchy.

  24. 24. What is a static method?

    Correct answer: A method that belongs to the class itself, not to its instances

    You call it as MathUtils.clamp(x) without creating an object. It has no this pointing to an instance, so it can't read instance fields.

  25. 25. What does this code print?

    class IdGenerator {
      static next = 1;
      id: number;
      constructor() {
        this.id = IdGenerator.next++;
      }
    }
    
    new IdGenerator();
    const g = new IdGenerator();
    console.log(g.id, IdGenerator.next);

    Correct answer: 2 3

    A static field is shared by the class, not copied per instance. The first object took 1, the second took 2, and the counter is now 3.

  26. 26. What are getters and setters for?

    Correct answer: To control access to a field: compute it, validate it or log the change

    A setter can reject a negative age, a getter can compute fullName from two fields. Callers still use simple property syntax.

  27. 27. Why is a class with a public getter and setter for every field weakly encapsulated?

    Correct answer: Outside code can still change any state freely, with no rules applied

    Encapsulation is about protecting rules, not about syntax. Methods like deposit() or rename() that enforce invariants hide more than plain accessors.

  28. 28. What does this code print?

    const a = { x: 1 };
    const b = { x: 1 };
    const c = a;
    console.log(a === b, a === c);

    Correct answer: false true

    === on objects compares references. a and b are two different objects with equal content, while c points to the same object as a.

  29. 29. In Java, what is the difference between == and equals() for objects?

    Correct answer: == compares references, equals() compares logical equality

    new String("a") == new String("a") is false, but equals() returns true. Classes override equals() to define what "equal" means for them.

  30. 30. In Java, if you override equals(), what else must you override?

    Correct answer: hashCode(), so equal objects have equal hash codes

    Hash-based collections like HashMap first compare hash codes. If two equal objects have different hashes, a lookup won't find the key.

  31. 31. What does instanceof check?

    Correct answer: Whether an object's prototype chain or class hierarchy includes the given type

    dog instanceof Animal is true because Dog extends Animal. Frequent instanceof checks in business code often signal missing polymorphism.

  32. 32. What is an immutable object?

    Correct answer: An object whose state can't change after it is created

    To "change" an immutable Money, you create a new one: price.add(tax) returns a new object. Strings in Java and Python work this way.

  33. 33. Why are immutable objects easier to work with?

    Correct answer: They can be shared safely, since no one can change them behind your back

    With immutable values you don't need defensive copies, and threads can read them without locks. A bug where one module mutates another's data can't happen.

  34. 34. What problem does this code have?

    class Order {
      items: string[] = [];
      getItems() {
        return this.items;
      }
    }
    
    const order = new Order();
    order.getItems().push("hacked");

    Correct answer: The getter leaks the internal array, so callers can change it

    Returning the internal array hands out a reference to the object's state. Return a copy or a read-only view, and add items through a method like addItem().

  35. 35. What does the S in SOLID stand for?

    Correct answer: Single Responsibility Principle

    SOLID is Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation and Dependency Inversion.

  36. 36. A UserService class validates input, saves users to the database, sends welcome emails and builds PDF reports. Which principle does it break most clearly?

    Correct answer: Single Responsibility

    The class has many reasons to change: a new email provider, a new report format, a schema change. Each concern belongs in its own class.

  37. 37. How does Robert Martin phrase the Single Responsibility Principle?

    Correct answer: A class should have only one reason to change

    The "reason to change" is a group of people or a business concern that asks for changes. The rule is not about counting methods or lines.

  38. 38. What does the Open/Closed Principle say?

    Correct answer: Code should be open for extension but closed for modification

    You add a new behavior by adding new code, such as a new class that implements an interface, instead of editing working code that is already tested.

  39. 39. Which code violates the Open/Closed Principle?

    function area(shape: Shape) {
      if (shape.type === "circle") return Math.PI * shape.r ** 2;
      if (shape.type === "square") return shape.side ** 2;
      // every new shape means a new if here
    }

    Correct answer: This function: each new shape forces you to edit it

    If every shape has its own area() method, adding a triangle means adding a class, not changing existing code. Note that a discriminated union with an exhaustive switch is a valid alternative when the set of types is closed.

  40. 40. What does the Liskov Substitution Principle require?

    Correct answer: Objects of a subclass must work wherever the parent type is expected

    If code works with a Bird, it must keep working when given any subclass. A subclass that throws where the parent worked breaks this promise.

  41. 41. Why does this hierarchy break LSP?

    class Bird {
      fly() { /* ... */ }
    }
    
    class Penguin extends Bird {
      fly() {
        throw new Error("Penguins can't fly");
      }
    }

    Correct answer: Code that calls bird.fly() crashes when it gets a Penguin

    The parent promises that every bird can fly. A better model splits the capability out, for example a FlyingBird type or a Flyer interface.

  42. 42. What does the Interface Segregation Principle say?

    Correct answer: Clients shouldn't depend on methods they don't use

    A big Worker interface with work(), eat() and sleep() forces a Robot to fake eat(). Several small interfaces let each class pick what it really supports.

  43. 43. A Printer interface has print(), scan() and fax(). A simple printer class has to throw from scan() and fax(). What is the fix?

    Correct answer: Split it into Printer, Scanner and Fax interfaces

    Small role interfaces let a multifunction device implement all three, while a basic printer implements only Printer. No class has to fake methods.

  44. 44. What does the Dependency Inversion Principle say?

    Correct answer: High-level modules should depend on abstractions, not on low-level details

    OrderService should depend on a PaymentGateway interface, not on StripeClient directly. Then the details can change without touching business logic.

  45. 45. Which version follows the Dependency Inversion Principle?

    Correct answer: constructor(private repo: UserRepository) {}, where UserRepository is an interface

    The class receives an abstraction from outside. In tests you pass an in-memory repository, in production a Postgres one, and the class doesn't change.

  46. 46. What is dependency injection?

    Correct answer: Passing an object's dependencies from outside instead of creating them inside

    The simplest form is constructor injection: new OrderService(paymentGateway, logger). A DI container only automates this wiring.

  47. 47. Why does dependency injection make a class easier to test?

    Correct answer: You can pass a fake or a stub instead of the real database or API

    A class that does new HttpClient() inside always hits the network. With injection, the test passes a fake client that returns prepared data.

  48. 48. What does "high cohesion" mean for a class?

    Correct answer: Its fields and methods are closely related and serve one purpose

    In a cohesive class most methods use most fields. A class where methods split into groups that never touch each other's data probably holds two classes.

  49. 49. What does "low coupling" between classes mean?

    Correct answer: Classes know little about each other, so a change in one rarely breaks another

    Low coupling means depending on small, stable interfaces instead of on internals. It doesn't mean no dependencies, which would be impossible.

  50. 50. What is a "God object"?

    Correct answer: A class that knows or does too much and is coupled to most of the system

    Classes like AppManager or Utils with thousands of lines grow because adding code there is easy. They are hard to test and change, and they break SRP.

  51. 51. What does DRY stand for?

    Correct answer: Don't Repeat Yourself

    DRY means each piece of knowledge should have one source of truth. It's about duplicated knowledge, not about every pair of lines that look alike.

  52. 52. A method takes (name, street, city, zip, country, phone, email). Which refactoring helps?

    Correct answer: Group related values into objects such as Address and Contact

    A long parameter list is a code smell. Parameter objects give the data a name, a place for validation and a single argument to pass around.

  53. 53. What is "primitive obsession"?

    Correct answer: Using strings and numbers for domain ideas like email, money or phone

    A price: number doesn't know its currency, an email: string accepts any text. A small Money or Email class keeps the rules in one place.

  54. 54. What is this inside a method called as user.greet()?

    Correct answer: The user object the method was called on

    In JavaScript, this is set by how a function is called. With obj.method() it's obj. Detached calls like const f = user.greet; f() lose it.

  55. 55. What does this code print?

    class Timer {
      seconds = 5;
      start() {
        setTimeout(function () {
          console.log(this.seconds);
        }, 0);
      }
    }
    
    new Timer().start();

    Correct answer: undefined, because a regular function callback has its own this

    A regular function gets its own this, which here isn't the Timer instance. An arrow function () => console.log(this.seconds) keeps the method's this and prints 5.

  56. 56. In Python, what is self in a method?

    Correct answer: The instance the method was called on, passed as the first argument

    obj.method(x) is equivalent to Class.method(obj, x). The name self is a convention, not a keyword, but everyone uses it.

  57. 57. In Python, what does __init__ do?

    Correct answer: Initializes a newly created instance

    __init__ sets up the fields of an object that already exists. The object itself is created by __new__, which you rarely need to override.

  58. 58. In Python, what does a leading underscore in self._cache mean?

    Correct answer: A convention: it's internal, outside code shouldn't use it

    Python has no access modifiers. _name signals "internal", and __name triggers name mangling to avoid clashes in subclasses, but neither is a hard wall.

  59. 59. What is duck typing?

    Correct answer: An object fits if it has the needed methods, whatever its declared type

    "If it walks like a duck and quacks like a duck": Python and JavaScript call obj.read() without checking the class. Anything with read() works.

  60. 60. Does this TypeScript code compile?

    interface Named {
      name: string;
    }
    
    class Cat {
      name = "Tom";
    }
    
    const n: Named = new Cat();

    Correct answer: Yes, TypeScript compares the shape, not the declared names

    TypeScript uses structural typing: Cat has a name: string, so it matches Named. Java and C# are nominal and would require implements.

  61. 61. What does implements give a TypeScript class?

    Correct answer: A compile-time check that the class matches the interface

    implements adds nothing at runtime. It only makes the compiler report missing or mismatched members right in the class declaration.

  62. 62. What does readonly on a TypeScript field do?

    Correct answer: The field can be set only in its declaration or in the constructor

    readonly is a compile-time check on reassignment of that one field. A readonly items: string[] can still be changed with push.

  63. 63. What does final on a Java class mean?

    Correct answer: The class can't be extended

    String is final, so nobody can create a subclass that changes its behavior. A final field can be assigned only once, and a final method can't be overridden.

  64. 64. What is the difference between aggregation and composition?

    Correct answer: In composition the part's lifetime depends on the whole, in aggregation it doesn't

    A House and its Rooms: delete the house and the rooms are gone (composition). A Team and its Players: players exist without the team (aggregation).

  65. 65. What does this code print?

    class Base {
      hello() {
        return "Base " + this.name();
      }
      name() {
        return "base";
      }
    }
    
    class Child extends Base {
      name() {
        return "child";
      }
    }
    
    console.log(new Child().hello());

    Correct answer: Base child

    hello() is inherited, but this.name() is dispatched on the real object, a Child. So the overridden name() runs.

  66. 66. What is a code smell?

    Correct answer: A sign in the code that often points to a deeper design problem

    Long methods, large classes and duplicated code aren't bugs, but they make change expensive. A smell is a hint to look closer, not an automatic verdict.

  67. 67. What is refactoring?

    Correct answer: Changing the internal structure of code without changing its behavior

    Refactoring is done in small, safe steps covered by tests: rename, extract method, move class. Behavior stays the same, design improves.

  68. 68. Why does a switch on an object's type repeated in many places hint at missing polymorphism?

    Correct answer: Each new type forces edits in every switch, instead of one new class

    If calculatePay, printBadge and vacationDays all switch on employee.type, the behavior belongs inside Engineer, Manager and so on.

  69. 69. What does an interface give the code that uses it?

    Correct answer: It can work with any implementation without knowing the concrete class

    A function that takes a Logger works with ConsoleLogger, FileLogger or a test double. The caller chooses, the function doesn't care.

  70. 70. In Java, what is the default toString() of an object that doesn't override it?

    Correct answer: The class name and a hex hash, like User@1b6d3586

    Object.toString() returns getClass().getName() + "@" + Integer.toHexString(hashCode()). Override it to get useful logs.

  71. 71. What is method overloading in TypeScript?

    Correct answer: Several call signatures for one function, with a single implementation

    TypeScript lets you declare signatures like parse(x: string) and parse(x: number), but there is only one body that checks the argument at runtime. Java picks among real separate methods.

  72. 72. What is a Java record?

    Correct answer: A compact immutable data class with generated equals, hashCode, toString

    record Point(int x, int y) {} gives final fields, a constructor, accessors and value-based equality in one line.

  73. 73. Which statement about OOP and classes is correct?

    Correct answer: OOP is about objects with state and behavior, classes are one way to define them

    JavaScript had objects and prototype-based inheritance long before class syntax, which is sugar over prototypes. Languages like Self had no classes at all.

  74. 74. Which line hints at a Law of Demeter violation?

    Correct answer: order.getCustomer().getAddress().getCity().toUpperCase()

    The caller digs through three objects it shouldn't know about. If the address structure changes, this line breaks. Asking order for what you need keeps the knowledge in one place.

  75. 75. In Python, how does a @classmethod differ from a regular method?

    Correct answer: It receives the class as its first argument (cls) instead of the instance

    Class methods are often used as alternative constructors, like Date.fromisoformat(s). Because they get cls, subclasses calling them get instances of the subclass.