Please enable JavaScript.
Coggle requires JavaScript to display documents.
Abstract Classes Vs Interfaces - Coggle Diagram
Abstract Classes Vs Interfaces
Abstract Class
Definition
Declared using "abstract" keyword
Cannot be instantiated directly
May contain abstract and non-abstract methods
Purpose
Provides a base for subclasses
Defines common behavior
Enforces method implementation in child classes
Characteristics
May include abstract methods (without body)
May include concrete methods (with body)
May have constructors, fields, and constants
Supports inheritance
Syntax
abstract class ClassName {
abstract void methodName(); // abstract method
void normalMethod() { ... } // concrete method
}
Example
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() { System.out.println("Drawing Circle"); }
}
Interface
Definition
Declared using "interface" keyword
Cannot be instantiated
Only contains abstract methods (till Java 7)
From Java 8: Can have default and static methods
From Java 9: Can have private methods
Purpose
Provides contract for classes
Supports multiple inheritance
Used for abstraction and polymorphism
Characteristics
Methods are public and abstract by default (Java 7)
Variables are public, static, and final
Supports multiple implementation
Syntax
interface InterfaceName {
void methodName();
}
class MyClass implements InterfaceName {
public void methodName() { ... }
}
Example
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() { System.out.println("Drawing Circle"); }
}
Comparison
Instantiation
Abstract Class: Cannot be instantiated
Interface: Cannot be instantiated
Methods
Abstract Class: Can have abstract + concrete methods
Interface: Only abstract methods (Java 7), default/static allowed (Java 8+)
Variables
Abstract Class: Instance and static variables allowed
Interface: Only public static final (constants)
Inheritance
Abstract Class: Single inheritance
Interface: Multiple inheritance (via multiple interfaces)
Constructor
Abstract Class: Can have constructors
Interface: Cannot have constructors