Search code examples
javainterfaceimplements

Java interface implementation?


I'm newbie to Java. I would like to ask different between the following interface examples?

public interface MyInterface {
  public void doSomething();
}

like this

public class MyClass implements MyInterface {
   public void doSomething {....}
}

and this

public class MyClass implements MyInterface {
    protected MyInterface myInterface;

public MyClass (MyInterface myInterface) {
    this.myInterface = myInterface;
  }

public void doSomething () {
    myInterface.doSomething();
  }
}

Solution

  • public class MyClass implements MyInterface {
       public void doSomething {....}
    }
    

    MyClass implements the interface MyInterface. It means your class holds a concrete behavior that your interface promise. By implementing the interface your class guaranteed the MyClass has the concrete feature your interface abstracted in its declaration.

    But I doubt you may not have a real scenario to implement an interface as well as create an instance of interface in a class. Second part of your question is one of the most famous design topic of inheritance vs composition. Chances of using both inheritance and composition together of an interface is barely rare.