Abstract class — partial implementation, single inheritance. Interface — pure contract (mostly), multiple inheritance.
Analogy: An abstract class is like a blueprint for a house — it has some rooms built (concrete methods) and some rooms left empty (abstract methods). An interface is like a building code/standard — it tells you what capabilities a building MUST have, but doesn't build anything itself.
Abstract class:
abstract keyword.super() from subclass).1abstract class Animal {2 // Instance field3 protected String name;45 // Constructor (interfaces can't have constructors)6 public Animal(String name) {7 this.name = name;8 }910 // Concrete method — provides default behavior11 public void sleep() {12 System.out.println(name + " is sleeping");13 }1415 // Abstract method — subclasses MUST implement16 public abstract void makeSound();1718 // Static method19 public static boolean isAnimal(Animal a) {20 return a != null;21 }22}2324class Dog extends Animal {25 public Dog(String name) {26 super(name);27 }2829 @Override30 public void makeSound() {31 System.out.println(name + " barks!");32 }33}3435// Animal a = new Animal("test"); // COMPILE ERROR: cannot instantiate36Animal a = new Dog("Rex");37a.sleep(); // Rex is sleeping38a.makeSound(); // Rex barks!
Interface:
interface keyword.public static final (constants) by default.default methods (with body) and static methods.private methods (helper methods for default methods).1interface Swimmable {2 void swim(); // public abstract by default34 // Default method (Java 8+)5 default void float_() {6 System.out.println("Floating gently");7 }8}910interface Flyable {11 void fly();1213 default void glide() {14 System.out.println("Gliding");15 }16}1718// A class can implement MULTIPLE interfaces19class Duck extends Animal implements Swimmable, Flyable {20 public Duck(String name) {21 super(name);22 }2324 @Override25 public void makeSound() {26 System.out.println("Quack!");27 }2829 @Override30 public void swim() {31 System.out.println("Duck swims in water");32 }3334 @Override35 public void fly() {36 System.out.println("Duck flies low");37 }38}3940Duck duck = new Duck("Donald");41duck.swim(); // Duck swims in water42duck.fly(); // Duck flies low43duck.glide(); // Gliding (default method)
Key differences:
When to use which:
Common mistake: Using an abstract class when you need multiple inheritance. Java doesn't allow extending multiple classes, but it does allow implementing multiple interfaces.