Java Interface: Defining Contracts with the implements Keyword

package Pack1;

interface games {
    public void outdoor();
    public void indoor();
}

class game_types implements games {
    public void outdoor() {
        System.out.println("Cricket");
    }
    public void indoor() {
        System.out.println("Table Tennis");
    }
}

public class my_interface {
    public static void main(String[] args) {
        games my_game = new game_types();
        my_game.outdoor();
        my_game.indoor();
    }
}

Output:

Cricket
Table Tennis

1. Implicit Compiler Rules for Java Interfaces 🔝

Interface Member Implicit Modifiers Added by Compiler Rule for Implementing Class
void outdoor(); public abstract Implementing method must be declared public.
int MAX = 10; public static final Compile-time constant; cannot be reassigned.
default void help() {} public default (Java 8+) Inherited automatically; optional to override.
static void util() {} public static (Java 8+) Called via InterfaceName.util(); not inherited.

2. Implementing Multiple Interfaces in One Class 🔝

While a Java class can extends only one parent class, it can implements any number of comma-separated interfaces—giving Java safe multiple inheritance of type:

interface Camera {
    void takePhoto();
}

interface MusicPlayer {
    void playTrack(String song);
}

 // A single class can implement multiple comma-separated interfaces:
class SmartPhone implements Camera, MusicPlayer {
    public void takePhoto() {
        System.out.println("Captured 48MP photo.");
    }
    public void playTrack(String song) {
        System.out.println("Playing: " + song);
    }
}

public class MultipleInterfaceDemo {
    public static void main(String[] args) {
        SmartPhone phone = new SmartPhone();
        phone.takePhoto();
        phone.playTrack("Java Blues");
    }
}

Terminal Output:

Captured 48MP photo.
Playing: Java Blues

3. Defining Constants Inside an Interface 🔝

Every variable declared inside an interface is automatically public static final, even if you omit those keywords:

interface AppConfig {
     // Implicitly public static final!
    int MAX_CONNECTIONS = 100;
    String DEFAULT_HOST = "localhost";
}

public class InterfaceConstantsDemo {
    public static void main(String[] args) {
        System.out.println("Host: " + AppConfig.DEFAULT_HOST);
        System.out.println("Max:  " + AppConfig.MAX_CONNECTIONS);
    }
}

Terminal Output:

Host: localhost
Max:  100

4. Java 8+ default and static Methods in Interfaces 🔝

Java 8 introduced default methods (allowing you to add new methods with a body to an existing interface without breaking older classes that implement it) and static utility methods:

interface Logger {
    void log(String msg);  // Abstract method

     // Java 8+ default method (inherited automatically, can be overridden):
    default void logInfo(String msg) {
        log("[INFO] " + msg);
    }

     // Java 8+ static helper method on the interface itself:
    static String version() { return "Logger v2.0"; }
}

public class ConsoleLogger implements Logger {
    public void log(String msg) { System.out.println(msg); }

    public static void main(String[] args) {
        System.out.println(Logger.version());
        new ConsoleLogger().logInfo("Server started");
    }
}

Terminal Output:

Logger v2.0
[INFO] Server started

5. Functional Interfaces (Single Abstract Method) & Lambdas 🔝

An interface with exactly one abstract method is a Functional Interface and can be instantiated concisely using a Java 8+ lambda expression (a, b) -> ...:

interface MathOperation {
    int compute(int a, int b);  // Single Abstract Method (Functional Interface)
}

public class FunctionalInterfaceDemo {
    public static void main(String[] args) {
        MathOperation adder = (a, b) -> a + b;
        MathOperation multiplier = (a, b) -> a * b;
        System.out.println("Lambda Add:      " + adder.compute(12, 8));
        System.out.println("Lambda Multiply: " + multiplier.compute(12, 8));
    }
}

Terminal Output:

Lambda Add:      20
Lambda Multiply: 96

6. Comparison: Interface vs Abstract Class 🔝

Capability interface abstract class
Keyword Used by Class class B implements A, C class B extends A (1 class only)
Mutable Instance Fields No (only static final constants) Yes (non-static fields)
Constructors No Yes (called via super())
Lambda Support Yes (if 1 abstract method) No

7. Production Recipe: Programming to an Interface (PaymentGateway) 🔝

Writing business logic against an interface reference (PaymentGateway) decouples your checkout service from concrete payment providers (UpiGateway, CardGateway):

interface PaymentGateway {
    void charge(int amount);
}

class UpiGateway implements PaymentGateway {
    public void charge(int amount) { System.out.println("Paid " + amount + " via UPI"); }
}

class CardGateway implements PaymentGateway {
    public void charge(int amount) { System.out.println("Paid " + amount + " via Credit Card"); }
}

public class CheckoutService {
    public static void main(String[] args) {
        PaymentGateway[] gateways = {new UpiGateway(), new CardGateway()};
        for (PaymentGateway gw : gateways) {
            gw.charge(500);
        }
    }
}

Terminal Output:

Paid 500 via UPI
Paid 500 via Credit Card

8. Common Developer Pitfalls & Traps 🔝

Forgetting public When Implementing an Interface Method

Inside interface games { void outdoor(); }, outdoor() is implicitly public! If you write void outdoor() { ... } inside class game_types without the public keyword, Java rejects it with: attempting to assign weaker access privileges; was public.

Diamond Conflict Between Two Identical default Methods

If a class implements two interfaces A and B that both define default void hello(), the compiler forces your class to override public void hello() and explicitly pick one (e.g., A.super.hello();).

9. Complete Compilable Java Program 🔝

public class OopInterfaceFullDemo {
    interface Measurable { int getScore(); }
    static class Exam implements Measurable {
        public int getScore() { return 95; }
    }
    public static void main(String[] args) {
        Measurable m = new Exam();
        if (m.getScore() == 95) {
            System.out.println("All Java interface verification checks passed! score=95");
        }
    }
}

Terminal Output:

All Java interface verification checks passed! score=95

10. Frequently Asked Questions (FAQ) 🔝

Can one interface extend another interface?

Yes! An interface uses the extends keyword (not implements) to inherit from one or more parent interfaces: interface Sports extends games, OutdoorEvents { ... }.

Can I instantiate an interface directly with new games()?

No, you cannot instantiate an interface by itself, though you can create an anonymous inner class or lambda expression, or instantiate a concrete implementing class (games g = new game_types();).

What happens if a class implements an interface but leaves out one method?

The class will fail to compile unless the class itself is declared abstract.

What is a marker (tag) interface in Java?

An empty interface with zero methods (such as java.io.Serializable or Cloneable) used to tag a class with metadata inspected by the JVM at runtime.

Can an interface have private methods?

Starting in Java 9, yes! Interfaces can contain private and private static helper methods to share code between multiple default methods inside the same interface.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer