[{"data":1,"prerenderedAt":115},["ShallowReactive",2],{"qa-\u002Fjava\u002Foop\u002Finterfaces-vs-abstract":3},{"page":4,"siblings":95,"blog":112},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"questionsCount":85,"related":86,"seo":87,"seoDescription":88,"stem":89,"subtopic":90,"topic":91,"topicSlug":92,"updated":93,"__hash__":94},"qa\u002Fjava\u002Foop\u002Finterfaces-vs-abstract.md","Interfaces Vs Abstract",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Java","java",{},true,4,"\u002Fjava\u002Foop\u002Finterfaces-vs-abstract",[23,28,32,36,40,44,48,52,56,60,64,68,72,77,81],{"id":24,"difficulty":25,"q":26,"a":27},"abstraction","easy","What is abstraction and how is it achieved in Java?","Abstraction is exposing a **simplified contract** while hiding implementation\ndetail. In Java you achieve it with **interfaces** (pure contract) and\n**abstract classes** (partial implementation). Callers depend on the abstract\ntype, not the concrete class.\n\n```java\ninterface PaymentGateway { void charge(int cents); }\n\nclass StripeGateway implements PaymentGateway {\n  public void charge(int cents) { \u002F* API calls hidden here *\u002F }\n}\n\nPaymentGateway gw = new StripeGateway(); \u002F\u002F code depends only on the contract\n```\n\nThe payoff is decoupling: you can swap `StripeGateway` for `PayPalGateway`\nwithout touching the calling code — the basis of \"program to an interface.\"\n",{"id":29,"difficulty":14,"q":30,"a":31},"abstract-vs-interface","What is the difference between an abstract class and an interface?","- **Abstract class** — can have state (fields), constructors, and a mix of\n  concrete and abstract methods. A class extends **one**. Models an\n  *is-a* with shared implementation.\n- **Interface** — a contract; historically only abstract methods, now also\n  `default`\u002F`static`\u002F`private` methods, but **no instance state** (only\n  `public static final` constants). A class implements **many**.\n\n```java\nabstract class Shape {\n  private String name;            \u002F\u002F state allowed\n  abstract double area();         \u002F\u002F subclasses must implement\n  String describe() { return name + \": \" + area(); }\n}\ninterface Drawable { void draw(); default void hide() { } }\n```\n\nRule of thumb: use an **interface** for a capability multiple unrelated classes\ncan have (`Comparable`, `Runnable`); use an **abstract class** when subclasses\nshare state or implementation and form a tight family.\n",{"id":33,"difficulty":25,"q":34,"a":35},"abstract-class-purpose","What is an abstract class and when can't you instantiate one?","An **abstract class** is declared `abstract` and **cannot be instantiated** with\n`new` — it exists to be extended. It can mix abstract methods (no body, must be\nimplemented) with concrete methods and fields, providing a partial\nimplementation subclasses complete.\n\n```java\nabstract class Animal {\n  abstract String sound();                 \u002F\u002F must override\n  void describe() { System.out.println(\"Says \" + sound()); } \u002F\u002F shared\n}\n\u002F\u002F Animal a = new Animal();  \u002F\u002F ERROR — abstract, can't instantiate\nAnimal a = new Dog();        \u002F\u002F OK via a concrete subclass\n```\n\nA class with **any** abstract method must itself be `abstract` (but an abstract\nclass can have zero abstract methods). **Rule of thumb:** abstract class =\n\"shared base you're not meant to use directly.\"\n",{"id":37,"difficulty":14,"q":38,"a":39},"abstract-constructor","Can an abstract class have a constructor?","Yes. Even though you can't `new` an abstract class directly, its constructor\n**runs when a subclass is instantiated**, via the implicit\u002Fexplicit `super(...)`\ncall — it initializes the abstract class's slice of the object.\n\n```java\nabstract class Shape {\n  final String name;\n  Shape(String name) { this.name = name; }   \u002F\u002F runs during subclass construction\n}\nclass Circle extends Shape {\n  Circle() { super(\"circle\"); }               \u002F\u002F must chain to it\n}\n```\n\nInterfaces, by contrast, **cannot** have constructors (no instance state to\ninitialize). **Rule of thumb:** abstract classes initialize shared state through\ntheir constructor; interfaces can't.\n",{"id":41,"difficulty":14,"q":42,"a":43},"interface-default","What are default methods in interfaces and why were they added?","A **default method** provides a body inside an interface using the `default`\nkeyword. They were added in Java 8 so interfaces could **evolve** — e.g. adding\n`forEach` to `Iterable` — **without breaking** every existing implementer.\n\n```java\ninterface Greeter {\n  String name();\n  default String greet() { return \"Hello, \" + name(); } \u002F\u002F optional to override\n}\n```\n\nIf a class inherits conflicting defaults from two interfaces, it **must\noverride** to resolve the ambiguity (it can call `Iface.super.method()`).\nInterfaces can also have `static` and `private` helper methods now — but still\nno instance state.\n",{"id":45,"difficulty":14,"q":46,"a":47},"interface-static-methods","Can an interface have static and private methods?","Yes (Java 8 added `static`, Java 9 added `private`):\n\n- **`static`** — utility methods called on the interface itself, not inherited\n  by implementers (e.g. `Comparator.comparing(...)`).\n- **`private`** \u002F `private static` — helper methods that share code **between**\n  `default`\u002F`static` methods without exposing it.\n\n```java\ninterface Validator {\n  boolean valid(String s);\n  static Validator notEmpty() { return s -> s != null && !s.isEmpty(); }\n  default boolean validAll(List\u003CString> xs) { return xs.stream().allMatch(this::valid); }\n}\n```\n\n**Rule of thumb:** `static` for factories\u002Futilities tied to the type, `private`\nto DRY up the bodies of default methods — interfaces are now mini-toolkits, not\njust contracts.\n",{"id":49,"difficulty":25,"q":50,"a":51},"interface-constants","Can interfaces have fields? What kind?","Only **constants**. Every field in an interface is implicitly `public static\nfinal`, so it must be assigned at declaration and can never change — there's\n**no instance state**.\n\n```java\ninterface Physics {\n  double SPEED_OF_LIGHT = 299_792_458;   \u002F\u002F implicitly public static final\n}\nPhysics.SPEED_OF_LIGHT;                    \u002F\u002F accessed via the interface\n```\n\nThe old \"constant interface\" pattern (implementing an interface just to inherit\nits constants) is an **anti-pattern** — use an `enum` or a `final` class with a\nprivate constructor instead. **Rule of thumb:** interfaces hold constants and\nbehavior, never mutable state.\n",{"id":53,"difficulty":14,"q":54,"a":55},"functional-interface","What is a functional interface?","A **functional interface** has exactly **one abstract method** (SAM — Single\nAbstract Method), so it can be the target type of a **lambda** or **method\nreference**. The `@FunctionalInterface` annotation makes the compiler enforce\nthe \"one abstract method\" rule.\n\n```java\n@FunctionalInterface\ninterface Transformer { String apply(String s); }\n\nTransformer upper = s -> s.toUpperCase();   \u002F\u002F lambda implements the SAM\nupper.apply(\"hi\");                           \u002F\u002F \"HI\"\n```\n\n`default`\u002F`static` methods don't count against the one-abstract-method limit.\nExamples: `Runnable`, `Comparator`, `Function`, `Predicate`. **Rule of thumb:**\none abstract method = lambda-compatible.\n",{"id":57,"difficulty":14,"q":58,"a":59},"marker-interface","What is a marker interface?","A marker interface has **no methods** — it just *tags* a class so that code (or\nthe JVM) can detect a capability at runtime via `instanceof`. Classic examples:\n`Serializable`, `Cloneable`, `RandomAccess`.\n\n```java\nclass Config implements Serializable { } \u002F\u002F \"this class may be serialized\"\n```\n\nThe JVM checks `if (obj instanceof Serializable)` before serializing. Modern\nJava often prefers **annotations** for metadata, but marker interfaces still\ngive you compile-time type checking and `instanceof` support that annotations\ndon't.\n",{"id":61,"difficulty":14,"q":62,"a":63},"interface-vs-abstract-when","Can a class implement multiple interfaces with the same method?","Yes. If two interfaces declare the **same abstract** method, one implementation\nsatisfies both. But if they provide **conflicting `default`** methods, the class\n**must override** to break the tie, optionally delegating with\n`Interface.super.method()`.\n\n```java\ninterface A { default String hi() { return \"A\"; } }\ninterface B { default String hi() { return \"B\"; } }\n\nclass C implements A, B {\n  @Override public String hi() {\n    return A.super.hi();   \u002F\u002F explicitly choose A's default\n  }\n}\n```\n\nThis is Java's controlled answer to the multiple-inheritance \"diamond problem\":\nmultiple *types* are allowed, but conflicting *behavior* must be resolved\nexplicitly.\n",{"id":65,"difficulty":14,"q":66,"a":67},"interface-multiple-inheritance","How do interfaces give Java a form of multiple inheritance?","A class can `implements` **many** interfaces, inheriting **multiple type\ncontracts** — and, since Java 8, multiple `default` **implementations**. That's\nmultiple inheritance of *type* and *behavior*, without multiple inheritance of\n*state* (which is what causes the classic diamond problem).\n\n```java\ninterface Swimmer { default void move() { System.out.println(\"swim\"); } }\ninterface Flyer   { default void glide() { System.out.println(\"glide\"); } }\nclass Duck implements Swimmer, Flyer { }   \u002F\u002F inherits both behaviors\n```\n\nBecause interfaces hold no instance fields, there's no ambiguous state to merge.\n**Rule of thumb:** interfaces = safe multiple inheritance of capability; classes\n= single inheritance of implementation.\n",{"id":69,"difficulty":14,"q":70,"a":71},"when-interface-vs-abstract","How do you decide between an interface and an abstract class?","Choose by what you need to share:\n\n- **Interface** — a *capability* that unrelated classes can have, multiple\n  inheritance of type, or a lambda target. No shared state.\n- **Abstract class** — a *family* of related classes sharing **fields, a\n  constructor, or substantial implementation**.\n\n```java\ninterface Comparable\u003CT> { int compareTo(T o); }   \u002F\u002F any class can be comparable\nabstract class HttpServlet { \u002F* shared request plumbing + state *\u002F }\n```\n\nThey combine well: declare the API as an interface, offer an\n`AbstractXxx` skeletal class for implementers (like `AbstractList`). **Rule of\nthumb:** default to an interface; reach for an abstract class only when you must\nshare state\u002Fimplementation.\n",{"id":73,"difficulty":74,"q":75,"a":76},"diamond-default","hard","If a class extends a class and implements an interface with the same method, which wins?","The **class** wins — \"**class always beats interface**.\" A concrete method\ninherited from a superclass takes priority over a `default` method from an\ninterface, even if the interface is \"more specific.\"\n\n```java\nclass Base { public String id() { return \"class\"; } }\ninterface Tagged { default String id() { return \"interface\"; } }\n\nclass Item extends Base implements Tagged { }\nnew Item().id();   \u002F\u002F \"class\" — superclass method wins over default\n```\n\nAmong *interfaces*, a more-specific interface's default beats a less-specific\none; ties must be resolved manually. **Rule of thumb:** superclass method >\ninterface default > you must override.\n",{"id":78,"difficulty":14,"q":79,"a":80},"enum-basics","What are enums and what can they do beyond constants?","An `enum` defines a fixed set of named instances. Unlike `int` constants,\nenums are **type-safe**, can have **fields, constructors, and methods**, and\neach constant can even override behavior.\n\n```java\nenum Planet {\n  EARTH(9.81), MARS(3.71);\n  private final double gravity;\n  Planet(double g) { this.gravity = g; }   \u002F\u002F constructor\n  double weight(double mass) { return mass * gravity; }\n}\nPlanet.MARS.weight(70);  \u002F\u002F type-safe, behavior attached\n```\n\nEnums are implicitly `final` singletons (one instance per constant), work in\n`switch`, provide `values()`\u002F`valueOf()`\u002F`ordinal()`, and are the recommended\nway to implement singletons.\n",{"id":82,"difficulty":14,"q":83,"a":84},"enum-implements-interface","Can an enum implement an interface or have abstract methods?","Yes. An enum can `implements` an interface, and it can declare **abstract\nmethods** that **each constant overrides** — giving per-constant behavior (a\nclean replacement for `switch` over the enum).\n\n```java\ninterface Op { int apply(int a, int b); }\nenum Math implements Op {\n  ADD { public int apply(int a, int b) { return a + b; } },\n  MUL { public int apply(int a, int b) { return a * b; } };\n}\nMath.ADD.apply(2, 3);   \u002F\u002F 5 — each constant has its own body\n```\n\nAn enum can't `extends` a class (it implicitly extends `java.lang.Enum`), but\ninterfaces are open to it. **Rule of thumb:** use constant-specific method bodies\nto attach behavior to enum values instead of branching on them.\n",15,null,{"description":11},"Java interfaces vs abstract classes interview questions — abstraction, default and static interface methods, functional and marker interfaces, multiple inheritance of behavior, interface constants, enums and when to use each.","java\u002Foop\u002Finterfaces-vs-abstract","Interfaces vs Abstract Classes","Object-Oriented Programming","oop","2026-06-19","BW88jLcXhdNT2Ca6gCGI0mGHs07YWnXKYoWi87ygqtY",[96,100,103,107,108],{"subtopic":97,"path":98,"order":99},"Classes & Objects","\u002Fjava\u002Foop\u002Fclasses-objects",1,{"subtopic":101,"path":102,"order":12},"Inheritance","\u002Fjava\u002Foop\u002Finheritance",{"subtopic":104,"path":105,"order":106},"Polymorphism","\u002Fjava\u002Foop\u002Fpolymorphism",3,{"subtopic":90,"path":21,"order":20},{"subtopic":109,"path":110,"order":111},"equals & hashCode","\u002Fjava\u002Foop\u002Fequals-hashcode",5,{"path":113,"title":114},"\u002Fblog\u002Fjava-interfaces-vs-abstract-classes","Java Interfaces vs Abstract Classes — When to Use Which",1782244115978]