[{"data":1,"prerenderedAt":118},["ShallowReactive",2],{"qa-\u002Fjava\u002Foop\u002Finheritance":3},{"page":4,"siblings":97,"blog":115},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":12,"path":20,"questions":21,"questionsCount":88,"related":89,"seo":90,"seoDescription":91,"stem":92,"subtopic":6,"topic":93,"topicSlug":94,"updated":95,"__hash__":96},"qa\u002Fjava\u002Foop\u002Finheritance.md","Inheritance",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Java","java",{},true,"\u002Fjava\u002Foop\u002Finheritance",[22,27,31,35,39,43,47,51,55,59,64,68,72,76,80,84],{"id":23,"difficulty":24,"q":25,"a":26},"four-pillars","easy","What are the four pillars of object-oriented programming?","- **Encapsulation** — bundle data with the methods that operate on it and hide\n  internal state behind a public API (private fields + getters\u002Fsetters).\n- **Abstraction** — expose *what* an object does, hide *how*, via interfaces\n  and abstract classes.\n- **Inheritance** — a subclass reuses and extends a superclass's members\n  (`extends`).\n- **Polymorphism** — one reference type, many runtime forms; the actual\n  object's overridden method is called.\n\n```java\nclass Animal { String sound() { return \"...\"; } }\nclass Dog extends Animal { String sound() { return \"Woof\"; } } \u002F\u002F inheritance + override\nAnimal a = new Dog();   \u002F\u002F polymorphism\na.sound();              \u002F\u002F \"Woof\"\n```\n\nA good one-liner: encapsulation hides data, abstraction hides complexity,\ninheritance reuses behavior, polymorphism varies it.\n",{"id":28,"difficulty":24,"q":29,"a":30},"inheritance","What is inheritance and what does Java not allow?","Inheritance lets a subclass acquire the fields and methods of a superclass with\n`extends`, modeling an **is-a** relationship and enabling reuse + polymorphism.\n\n```java\nclass Vehicle { void start() { } }\nclass Car extends Vehicle { void honk() { } } \u002F\u002F Car is-a Vehicle\n```\n\nJava allows **single inheritance** of classes only — a class can extend exactly\none superclass (to avoid the \"diamond problem\"). It *can* implement **multiple\ninterfaces**, which is how Java gets multiple-type flexibility without\nmultiple class inheritance. `final` classes can't be extended at all.\n",{"id":32,"difficulty":24,"q":33,"a":34},"object-superclass","What is the Object class and what does every class inherit from it?","`java.lang.Object` is the **root** of every class hierarchy — if you don't\n`extends` anything, you implicitly extend `Object`. So every object has its\nmethods, the most important being:\n\n- `equals(Object)` \u002F `hashCode()` — value equality and hashing.\n- `toString()` — string representation.\n- `getClass()` — the runtime class.\n- `clone()`, `finalize()` (deprecated), and the `wait`\u002F`notify` family for\n  threading.\n\n```java\nclass Foo { }            \u002F\u002F implicitly: class Foo extends Object\nObject o = new Foo();\no.toString();            \u002F\u002F \"Foo@1b6d3586\" by default\n```\n\n**Rule of thumb:** because everything is-an `Object`, an `Object` reference (or\n`Object[]`) can hold anything — the basis of pre-generics collections.\n",{"id":36,"difficulty":24,"q":37,"a":38},"types-of-inheritance","What types of inheritance does Java support?","- **Single** — one subclass, one superclass. ✅\n- **Multilevel** — a chain (`C extends B extends A`). ✅\n- **Hierarchical** — many subclasses of one parent. ✅\n- **Multiple inheritance of *classes*** — extending two classes. ❌ (not allowed)\n- **Multiple inheritance of *types*** — implementing many interfaces. ✅\n\n```java\nclass A { }\nclass B extends A { }            \u002F\u002F single\nclass C extends B { }            \u002F\u002F multilevel\nclass D extends A { }            \u002F\u002F hierarchical (with B)\nclass E implements I1, I2 { }    \u002F\u002F multiple interfaces — OK\n```\n\n**Rule of thumb:** Java forbids multiple *class* inheritance but allows multiple\n*interface* inheritance — you get many capabilities, but a single implementation\nlineage.\n",{"id":40,"difficulty":14,"q":41,"a":42},"why-no-multiple-inheritance","Why doesn't Java support multiple inheritance of classes?","To avoid the **diamond problem**: if `B` and `C` both extended `A` and overrode\na method, and `D` extended both `B` and `C`, the compiler couldn't tell **which\nversion** `D` inherits. C++ allows it and pays for it with complexity (virtual\ninheritance).\n\n```java\n\u002F\u002F Hypothetical — illegal in Java:\n\u002F\u002F class D extends B, C { }   \u002F\u002F which greet() does D get?\ninterface B { default String greet() { return \"B\"; } }\ninterface C { default String greet() { return \"C\"; } }\nclass D implements B, C {\n  public String greet() { return B.super.greet(); } \u002F\u002F YOU resolve it\n}\n```\n\nJava permits multiple *interface* inheritance because conflicting `default`\nmethods **force the class to resolve the ambiguity explicitly**. **Rule of\nthumb:** Java trades raw power for predictability.\n",{"id":44,"difficulty":14,"q":45,"a":46},"super-keyword","What does the super keyword do?","`super` refers to the **immediate superclass**. It does two jobs: call the\nparent **constructor** (`super(args)`, must be the first statement) and call an\n**overridden** parent method or access a parent field (`super.method()`).\n\n```java\nclass Animal {\n  Animal(String name) { }\n  void describe() { System.out.println(\"an animal\"); }\n}\nclass Dog extends Animal {\n  Dog(String name) {\n    super(name);              \u002F\u002F chain to parent constructor\n  }\n  @Override void describe() {\n    super.describe();         \u002F\u002F reuse parent behavior\n    System.out.println(\"...specifically a dog\");\n  }\n}\n```\n\nIf you don't call `super(...)` explicitly, the compiler inserts a no-arg\n`super()` — which fails to compile if the parent has no no-arg constructor.\n",{"id":48,"difficulty":14,"q":49,"a":50},"constructor-not-inherited","Are constructors inherited? How are they involved in inheritance?","**No** — constructors are not inherited. But every subclass constructor **must**\ninvoke a superclass constructor first, via an explicit `super(...)` or an\nimplicit no-arg `super()` the compiler inserts.\n\n```java\nclass Base {\n  Base(int id) { }            \u002F\u002F no no-arg constructor\n}\nclass Sub extends Base {\n  Sub() { super(1); }         \u002F\u002F MUST call super(int) explicitly\n  \u002F\u002F Sub() { }                \u002F\u002F would NOT compile — implicit super() missing\n}\n```\n\nSo if a parent defines only parameterized constructors, the child is **forced**\nto call one. **Rule of thumb:** inheritance reuses *methods and fields*, not\nconstructors — the child builds the parent's slice of itself by chaining up.\n",{"id":52,"difficulty":14,"q":53,"a":54},"upcasting-downcasting","What is the difference between upcasting and downcasting?","- **Upcasting** — treating a subclass object as its superclass type. Always\n  safe, implicit. Enables polymorphism.\n- **Downcasting** — casting a superclass reference back to a subclass. Needs an\n  **explicit cast** and can throw `ClassCastException` if the object isn't\n  actually that subtype — guard it with `instanceof`.\n\n```java\nAnimal a = new Dog();          \u002F\u002F upcast — implicit, safe\nDog d = (Dog) a;               \u002F\u002F downcast — explicit\nif (a instanceof Cat c) {      \u002F\u002F pattern: test before casting\n  c.meow();\n}\n```\n\n**Rule of thumb:** upcast freely to program to the supertype; downcast rarely,\nand only after an `instanceof` check.\n",{"id":56,"difficulty":24,"q":57,"a":58},"instanceof","What does the instanceof operator do?","`instanceof` tests whether an object is an instance of a given type (or subtype),\nreturning a `boolean`. Since Java 16, **pattern matching** lets you bind a\nvariable in the same expression, avoiding a separate cast.\n\n```java\nObject o = \"hello\";\nif (o instanceof String) { }            \u002F\u002F classic\nif (o instanceof String s) {            \u002F\u002F pattern matching\n  System.out.println(s.length());       \u002F\u002F s is already a String\n}\n```\n\n`null instanceof X` is always `false`. **Rule of thumb:** heavy `instanceof`\nchains are often a smell — prefer polymorphism (let each type implement the\nmethod) unless you're at a true type boundary (deserialization, `equals`).\n",{"id":60,"difficulty":61,"q":62,"a":63},"inheritance-vs-composition","hard","When should you favor composition over inheritance?","**Inheritance** (is-a) tightly couples a subclass to its parent's\nimplementation; changes to the base can silently break subclasses (the \"fragile\nbase class\" problem). **Composition** (has-a) builds behavior by *holding*\nother objects and delegating — looser coupling, more flexible.\n\n```java\n\u002F\u002F inheritance misused: a Stack is-a List? leaks all List methods\nclass Stack\u003CT> extends ArrayList\u003CT> { }\n\n\u002F\u002F composition: Stack HAS a list, exposes only stack operations\nclass Stack\u003CT> {\n  private final List\u003CT> items = new ArrayList\u003C>();\n  void push(T t) { items.add(t); }\n  T pop() { return items.remove(items.size() - 1); }\n}\n```\n\nGuideline (\"favor composition over inheritance\"): use inheritance only for a\ntrue is-a with a stable base designed for extension; otherwise compose. It also\nsidesteps single-inheritance limits.\n",{"id":65,"difficulty":24,"q":66,"a":67},"ducktyping-isa-hasa","What is the difference between an is-a and a has-a relationship?","- **is-a** -> inheritance. A `Car` *is a* `Vehicle` -> `class Car extends\n  Vehicle`.\n- **has-a** -> composition\u002Faggregation. A `Car` *has an* `Engine` -> the `Car`\n  holds an `Engine` field.\n\n```java\nclass Engine { }\nclass Car extends Vehicle {   \u002F\u002F is-a Vehicle\n  private final Engine engine = new Engine(); \u002F\u002F has-a Engine\n}\n```\n\nModeling tip: if you can't truthfully say \"X is a Y,\" don't use inheritance —\nreach for has-a (composition) instead. Misusing is-a (e.g. `Stack extends\nVector`) is a classic design smell.\n",{"id":69,"difficulty":14,"q":70,"a":71},"aggregation-vs-composition","What is the difference between aggregation and composition?","Both are **has-a**, differing in **lifecycle ownership**:\n\n- **Composition** — the part *can't exist* without the whole; the whole owns and\n  creates it (a `House` and its `Room`s). Strong ownership.\n- **Aggregation** — the part can exist independently and may be shared (a `Team`\n  and its `Player`s; players outlive the team).\n\n```java\nclass House {\n  private final Room room = new Room();   \u002F\u002F composition: created\u002Fowned here\n}\nclass Team {\n  private final List\u003CPlayer> players;      \u002F\u002F aggregation: passed in, shared\n  Team(List\u003CPlayer> players) { this.players = players; }\n}\n```\n\n**Rule of thumb:** \"owns and destroys together\" = composition; \"references but\ndoesn't own\" = aggregation.\n",{"id":73,"difficulty":14,"q":74,"a":75},"prevent-inheritance","How do you prevent a class from being subclassed?","Three ways, by strength:\n\n- **`final` class** — outright bans `extends` (e.g. `String`).\n- **`private`\u002Fpackage-private constructors** — no outside subclass can call\n  `super(...)`, so it can't be extended elsewhere.\n- **`sealed` class** (Java 17+) — allows only a named `permits` list of\n  subclasses.\n\n```java\nfinal class Money { }                          \u002F\u002F no subclasses at all\nsealed class Shape permits Circle, Square { }  \u002F\u002F only these two\n```\n\nReasons: protect invariants (an immutable class shouldn't be subclassed into\nmutability), security, and clearer design. **Rule of thumb:** design for\ninheritance *and document it*, or prohibit it with `final`\u002F`sealed`.\n",{"id":77,"difficulty":14,"q":78,"a":79},"cohesion-coupling","What are cohesion and coupling?","- **Cohesion** — how focused a class is on a single responsibility. **High\n  cohesion is good**: a `UserValidator` that only validates users.\n- **Coupling** — how dependent classes are on each other's internals. **Low\n  coupling is good**: classes interact through small, stable interfaces.\n\n```java\n\u002F\u002F low coupling: depends on an interface, not a concrete logger\nclass OrderService {\n  private final Logger log;            \u002F\u002F injected abstraction\n  OrderService(Logger log) { this.log = log; }\n}\n```\n\nThe goal of good OO design is **high cohesion, low coupling** — classes that do\none thing well and lean on each other as little as possible, which makes systems\neasier to change and test.\n",{"id":81,"difficulty":61,"q":82,"a":83},"liskov","What is the Liskov Substitution Principle?","The **L** in SOLID: a subtype must be usable **anywhere its supertype is\nexpected**, without breaking the program's correctness. A subclass that\nstrengthens preconditions, weakens postconditions, or throws on inherited\noperations violates it.\n\n```java\n\u002F\u002F Classic violation: Square is-a Rectangle?\nclass Rectangle { void setWidth(int w){} void setHeight(int h){} }\nclass Square extends Rectangle {\n  void setWidth(int w){ \u002F* also sets height — breaks setWidth's contract *\u002F }\n}\n\u002F\u002F code that sets width then expects height unchanged now fails\n```\n\nThe fix is usually composition or a shared abstraction, not inheritance. **Rule\nof thumb:** if a subclass can't honor everything the parent promises, it\nshouldn't extend it.\n",{"id":85,"difficulty":61,"q":86,"a":87},"solid","What do the SOLID principles stand for?","Five OO design principles for maintainable code:\n\n- **S** — Single Responsibility: a class has one reason to change.\n- **O** — Open\u002FClosed: open for extension, closed for modification.\n- **L** — Liskov Substitution: subtypes must be usable wherever their base is.\n- **I** — Interface Segregation: prefer small, specific interfaces over fat ones.\n- **D** — Dependency Inversion: depend on abstractions, not concretions.\n\n```java\n\u002F\u002F Dependency Inversion: high-level code depends on an interface\ninterface Repository { void save(Order o); }\nclass OrderService {\n  private final Repository repo;       \u002F\u002F not a concrete DB class\n  OrderService(Repository repo) { this.repo = repo; }\n}\n```\n\nLiskov is the one interviewers probe most: a subclass that throws on, or\nweakens, an inherited method (the `Square extends Rectangle` problem) violates\nit.\n",16,null,{"description":11},"Java inheritance interview questions — extends and super, single vs multiple inheritance, the Object superclass, is-a vs has-a, composition over inheritance, upcasting and downcasting, Liskov substitution and SOLID.","java\u002Foop\u002Finheritance","Object-Oriented Programming","oop","2026-06-19","5xZiWFIeS1BBeBN1394_sjmozGSS0qp9FdmN-_BRl9o",[98,102,103,107,111],{"subtopic":99,"path":100,"order":101},"Classes & Objects","\u002Fjava\u002Foop\u002Fclasses-objects",1,{"subtopic":6,"path":20,"order":12},{"subtopic":104,"path":105,"order":106},"Polymorphism","\u002Fjava\u002Foop\u002Fpolymorphism",3,{"subtopic":108,"path":109,"order":110},"Interfaces vs Abstract Classes","\u002Fjava\u002Foop\u002Finterfaces-vs-abstract",4,{"subtopic":112,"path":113,"order":114},"equals & hashCode","\u002Fjava\u002Foop\u002Fequals-hashcode",5,{"path":116,"title":117},"\u002Fblog\u002Fjava-oop-inheritance-polymorphism-encapsulation","Java OOP — Inheritance, Polymorphism, Abstraction & Encapsulation",1782244115352]