Java 7 Interface
🔹 Abstract Class Recap (Used for Comparison)
abstract class Geometry {
static final double PI = 3.14;
abstract double area();
abstract double circumference();
}
Abstract class can have both:
Abstract methods (no body)
Concrete methods (with body)
Cannot create object of abstract class.
Must override all abstract methods in subclass or mark subclass as abstract.
🔹 Example: Inheriting from Abstract Class
class Circle extends Geometry {
double r;
Circle(double r) { this.r = r; }
double area() { return PI * r * r; }
double circumference() { return 2 * PI * r; }
}
You can do similar for:
Rectangle (using length and width )
Ellipse (using major and minor axis)
Java 7 Interface 1
🔹 Runtime Polymorphism (Dynamic Binding)
Geometry[] shapes = { new Circle(2), new Rectangle(4, 5), new Ellipse(2, 3) };
for (Geometry g : shapes) {
[Link]([Link]());
}
👉 The correct area() method is called at runtime depending on object type
(Circle, Rectangle, etc.).
🧩 Interface – The Main Topic
🔹 What is an Interface?
Like an abstract class, but more strict.
Cannot have concrete methods.
All methods are implicitly:
public
abstract
All variables are implicitly:
public
static
final (constants)
🔹 Syntax of Interface
interface Shape {
void draw();
Java 7 Interface 2
void resize();
}
You cannot do:
int x = 10; // without static final
void show() { } // with body ❌
🔹 Implementing Interface in a Class
class Circle implements Shape {
public void draw() {
[Link]("Drawing Circle");
}
public void resize() {
[Link]("Resizing Circle");
}
}
🔹 Interface = Multiple Inheritance Solution
Java doesn't support multiple inheritance using classes, but allows it with
interfaces:
interface A {
void methodA();
}
interface B {
void methodB();
Java 7 Interface 3
}
class MyClass implements A, B {
public void methodA() { ... }
public void methodB() { ... }
}
✅ Java allows implementing multiple interfaces.
❌ You can't extend multiple classes.
🔹 Interface vs Abstract Class
Feature Interface Abstract Class
Methods Only abstract (no body) Can be abstract or normal
Variables public static final only Can be any type
Constructors ❌ Not allowed ✅ Allowed
Multiple Inheritance ✅ Yes (multiple interfaces) ❌ No
Keywords used interface , implements abstract , extends
Object Creation ❌ Not possible ❌ Not possible
🔹 Interface Inheritance
interface A {
void show();
}
interface B extends A {
void display();
}
One interface can extend one or more interfaces.
Java 7 Interface 4
🔹 Example with Interface and Polymorphism
interface GeoAnalyzer {
double area();
double perimeter();
}
class Circle implements GeoAnalyzer {
double r;
Circle(double r) { this.r = r; }
public double area() { return [Link] * r * r; }
public double perimeter() { return 2 * [Link] * r; }
}
class Main {
public static void main(String[] args) {
GeoAnalyzer shape = new Circle(5);
[Link]([Link]()); // Polymorphic call
[Link]([Link]());
}
}
Java 7 Interface 5