allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œHe gives strength to the weary and increases the power of the weak.โ€
[Isaiah 40:29]


Interfaces 


13.2.1 What is an Interface?

An interface in Java is like a pure abstraction.
Itโ€™s a contract that says: โ€œAny class that implements me promises to provide these methods.โ€

Key difference from abstract class:

  • An interface has no fields (except static final constants).

  • All methods are abstract by default (until Java 8 โ€” newer Java allows default and static methods too).

  • A class can implement multiple interfaces, but can extend only one class.


Why use interfaces?

  • To design common behaviors that unrelated classes can share.

  • To support multiple inheritance of type (Java does not support multiple inheritance of classes, but you can implement many interfaces).

  • To keep your code flexible and testable โ€” itโ€™s easy to swap implementations.


13.2.2 How to Declare and Implement an Interface

Declaring an interface:

java
public interface Animal { void makeSound(); void eat(); }
  • makeSound() and eat() have no body.

  • Any class that implements Animal must define both methods.

Implementing an interface:

java
public class Dog implements Animal { @Override public void makeSound() { System.out.println("Woof! Woof!"); } @Override public void eat() { System.out.println("Dog is eating."); } public static void main(String[] args) { Dog d = new Dog(); d.makeSound(); d.eat(); } }

Key points:

  • Use implements to connect class to interface.

  • Use @Override for each method.

  • The compiler checks that you implemented all methods.


13.2.3 Mini Lab: Combining Abstract Class + Interface

In real projects, you often combine both.

Example:

java
public interface Pet { void play(); } public abstract class Animal { String name; abstract void makeSound(); } public class Dog extends Animal implements Pet { @Override void makeSound() { System.out.println(name + " says: Woof!"); } @Override public void play() { System.out.println(name + " is playing fetch!"); } public static void main(String[] args) { Dog d = new Dog(); d.name = "Buddy"; d.makeSound(); d.play(); } }

How this works:

  • Animal defines common blueprint for all animals.

  • Pet defines extra behavior for pets.

  • Dog combines both โ€” itโ€™s an Animal that is also a Pet.