Sobes.tech
Middle

What is the difference between default methods and static methods?

sobes.tech AI

Answer from AI

Default methods and static methods were added to interfaces in Java 8. Main differences:

  • Access to object state: Default methods have access to the instance fields of the implementing class. Static methods do not have such access and operate only with static interface state or call parameters.
  • Overriding: Default methods can be overridden in implementing classes. Static interface methods cannot be overridden.
  • Invocation: Default methods are called on instances of implementing classes. Static methods are called directly on the interface name.

Example:

interface MyInterface {

    String instanceField = "instance"; // Instance field (not allowed in interfaces before Java 8)
    static String staticField = "static"; // Static field

    // Default method - has access to instance state (via instance methods, for example)
    default void defaultMethod() {
        System.out.println("Default method");
        // System.out.println(instanceField); // Cannot access directly
        instanceMethod(); // Can call instance methods
    }

    // Static method - does not have access to instance state.
    static void staticMethod() {
        System.out.println("Static method");
        System.out.println(staticField); // Has access to staticField
    }

    // Abstract method - must be implemented in class
    void instanceMethod();
}

class MyClass implements MyInterface {

    private String myInstanceField = "My class instance field";

    @Override
    public void instanceMethod() {
        System.out.println("Instance method from MyClass");
        System.out.println(myInstanceField);
    }

    // Override default method
    @Override
    public void defaultMethod() {
        System.out.println("Overridden default method in MyClass");
        instanceMethod(); // Call instanceMethod
    }
}

class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.defaultMethod(); // Call default method on instance (overridden in this case)
        // obj.staticMethod(); // Cannot call static method on instance

        MyInterface.staticMethod(); // Call static method on interface
    }
}
What is the difference between default methods and… - sobes.tech