Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Understanding Interface In Java

In this lesson, you will learn

  • Interface in Java
  • Key Features of Interface in Java
  • Defining Interface
  • Examples: Implementing Interface
  • Extending Interface
  • Examples: Extending Interface

 

Interface2

Interface in Java

  1. An interface is a reference type, similar to a class, it can contain methods and variables but with a major difference, the interface contains only abstract method and final fields.
  2. The classes that use the interface must implement all the interface methods.
  3. Interfaces cannot contain instance fields, instance methods, or constructors.
  4. All fields declared in the interface are implicitly public, static, and final.
  5. A 100% abstraction in Java can be achieved through interfaces.
  6. An interface method can not be final, static, native, private, or protected.
  7. It specifies “what” a class should do, but not “how” it should do it.

 

Key Features of Interface in Java

Interfaces in Java are powerful constructs that provide a way to achieve abstraction and define contracts. Here’s a breakdown of their key features:

InterfaceKeyFeatures

 

1. Abstract Methods:

  • Core Feature:
    • It contains abstract methods. These methods are declared without any implementation (no method body).
  • Forced Implementation:
    • Any class that implements an interface must provide concrete implementations for all of its abstract methods. This enforces a consistent behavior across different classes.
  • Example:
    • void calculateArea();

2. Constants (Static Final Variables):

  • Implicitly Public, Static, and Final:
    • Variables declared in an interface are implicitly public, static, and final. This means they are constants and cannot be changed.
  • Shared Values:
    • These constants can be used by any class that implements the interface.
  • Example:
    • int MAX_VALUE = 100;

3. Default Methods (Java 8 and Later):

  • Providing Default Implementation:
    • Java 8 introduced default methods, which allow you to provide a default implementation for a method within an interface.
  • Backward Compatibility:
    • This feature was added to enable adding new methods to existing interfaces without breaking the code of classes that already implement those interfaces.
  • Example:
    • default void printMessage() { System.out.println("Default message"); }

4. Static Methods (Java 8 and Later):

  • Interface-Specific Utility Methods:
    • Java 8 also introduced static methods in interfaces. These methods are associated with the interface itself and can be called directly using the interface name.
  • Utility Functions:
    • They are often used to provide utility functions related to the interface.
  • Example:
    • static int calculateSquare(int x) { return x * x; }

5. Multiple Inheritance (of Type):

  • Implementing Multiple Interfaces:
    • A class can implement multiple interfaces, allowing it to inherit multiple types and behaviors.
  • Achieving Polymorphism:
    • This provides a form of multiple inheritance, allowing objects of different classes to be treated as objects of the same interface type.
  • Example:
    • class MyClass implements InterfaceA, InterfaceB { ... }

6. Abstraction:

  • 100% Abstraction (with abstract methods):
    • Interfaces, when only abstract methods are used, provide 100% abstraction by defining what a class should do without specifying how.
  • Hiding Implementation Details:
    • They hide the implementation details and expose only the required functionality.

7. Contracts:

  • Defining a Contract:
    • An interface defines a contract that classes must adhere to. Any class that implements an interface must provide implementations for all of its abstract methods.
  • Ensuring Consistency:
    • This ensures consistency and predictability in the behavior of different classes that implement the same interface.
  •  

In summary, interfaces in Java are designed to promote abstraction, enforce contracts, and enable a form of multiple inheritance, contributing to cleaner, more flexible, and maintainable code.

 

How to Declare an Interface:

You declare an interface using the interface keyword. Here’s the basic syntax:

Syntax

public interface MyInterface {
    // Constant declarations
    int MY_CONSTANT = 10;

    // Abstract method declarations
    void myMethod();

    // Default method (Java 8 and later)
    default void myDefaultMethod() {
        // Default implementation
    }

    // Static method (Java 8 and later)
    static void myStaticMethod() {
        // Static implementation
    }
}

Note: When no access modifier is included, then default access results, and the interface is only available to other members of the package in which it is declared.

 

Example: Defining Interface

interface item
{
     static final int n=1001;
     static final String name="Alice";
     void display();
}

 

interface Area
{
     static final float pi=3.14f;
     float compute (float x, float y);
     void show();
}

 

Implementing Interface by a Class

Implementing an interface in Java involves creating a class that agrees to fulfill the contract defined by the interface. Here is the syntax

Syntax

class class-name implements Interface1, Interface2, ...
{
    //Class Body
}

 

Example 1: Implementing Interface: Animal Hierarchy

package ch10.l4;

//Define an interface
interface Animal {
	 // Interface method (does not have a body)
	 void eat();
	 void sleep();
	 
	 // Default method with a body (Java 8+)
	 default void breathe() {
	     System.out.println("Breathing");
	 }
}

//Implement the interface with a class
class Dog implements Animal {
	 // The body of eat() is provided here
	 public void eat() {
	     System.out.println("Dog is eating");
	 }
 
	 // The body of sleep() is provided here
	 public void sleep() {
	     System.out.println("Dog is sleeping");
	 }
}

public class AnimalAccess {
 public static void main(String[] args) {
     Dog myDog = new Dog();
     
     // Call the method on the dog object
     myDog.eat();
     myDog.sleep();
     myDog.breathe(); // Default method can be called
 }
}

Output

Dog is eating
Dog is sleeping
Breathing

Explanation

In this example, Animal is an interface with two methods eat() and sleep() that do not have bodies, which means they are abstract methods.

The Dog class implements the Animal interface, meaning it must provide implementations for the eat() and sleep() methods.

Additionally, the Animal interface has a default method breathe() with a body, which the Dog class inherits and can be used without providing its own implementation.

 

Example 2: Implementing Interface: Shape Hierarchy

package ch10.l4;

interface Shape {
    // Static field
    int MAX_SHAPES = 100; // Example static field (constant)

    // Abstract methods
    double calculateArea();
    double calculatePerimeter();

    // Default method with a body (Java 8+)
    default void printDetails() {
        System.out.println("Area: " + calculateArea());
        System.out.println("Perimeter: " + calculatePerimeter());
    }

    // Static method (Java 8+)
    static int getMaxShapes() {
        return MAX_SHAPES;
    }
}

class Circle implements Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double calculateArea() {
        return Math.PI * radius * radius;
    }

    @Override
    public double calculatePerimeter() {
        return 2 * Math.PI * radius;
    }
}

class Rectangle implements Shape {
    private double length;
    private double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    @Override
    public double calculateArea() {
        return length * width;
    }

    @Override
    public double calculatePerimeter() {
        return 2 * (length + width);
    }
}

public class AccessShapes {

	public static void main(String[] args) {
		Shape circle = new Circle(5);
        Shape rectangle = new Rectangle(10, 5);

        // Use the default method
        System.out.println("Circle Details:");
        circle.printDetails();

        System.out.println("Rectangle Details:");
        rectangle.printDetails();

        // Use the static method
        System.out.println("Maximum number of shapes: " + Shape.getMaxShapes());
	}
}

Output

Circle Details:
Area: 78.53981633974483
Perimeter: 31.41592653589793
Rectangle Details:
Area: 50.0
Perimeter: 30.0
Maximum number of shapes: 100

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

5.0
5.0 out of 5 stars (based on 1 review)
Excellent100%
Very good0%
Average0%
Poor0%
Terrible0%

 

 

04/04/2025

Very nice videos, i always study for my exams from here, the course is very detailed and helpful

 

 

Submit a Review