DEV Community

Prasanth
Prasanth

Posted on • Edited on

Interface

What is an Interface in Java?

Interface in java called blueprint of a class or reference type ,that contains only abstract methods(method without body)(until java 7) and can also contain default/static methods(from java 8)

why interface say reference type in java?

In java reference type means variable does not hold the actual value it is pointing to the object memory. so you can not create object in interface ,but you can use it a reference of the object of a class when implements . like you using class and array

Example:

Vehicle honda = new Car();

Vehicle = interface (or superclass) -> reference type
honda =  variable ( reference variable) -> to point s the object
new car() = object/instace -> Actual object in memory  

Enter fullscreen mode Exit fullscreen mode

why interface called blueprint of a class?

Interface defines what a class should do, not how.
That mean (do) you must have fallow the method name and signature(override) from the interface. (not how) interface does not say what code or logic to write inside that implement method, so interface rule is what should be done but not how ti should be done.

Example:-

interface Vehicle // when implement any class you should override the abstract method but not how.
{
void start(); 
}

class Car implements Vehicle
{
public void start()
{
System.out.println("Car start with key");
}
}  

class Bike implements Vehicle
{
public void start()
{
System.out.println("Bike start with key and kick..etc ");
}
}

public class ShowRoom
{
    public static void main(String[] args) {
Vehicle car1 = new Car(); //interface reference pointing to Car object.
}

}

// must to implement the method
// but not how like whether key or key and kick 
Enter fullscreen mode Exit fullscreen mode

Spring Boot real-world interface used with @Autowired (Loose coupling- does not depend directly ) we will see later.

Why Interface is Called a Contract?

  • You must implement all abstract methods from the interface, otherwise your class will not compile.

  • Interface contain static constants and abstract method. static constants mean all variables in interface by default public static final ,even if you do not write them, it mean fixed value , shared and accessible without object.

interface Contract {
    int VALUE = 100; // same as: public static final int VALUE = 100;
}

Enter fullscreen mode Exit fullscreen mode

Why use Interfaces?

  • To achieve 100% abstraction (before java 8)
  • To support multiple inheritance(java does not support multiple inheritance) Loose coupling between classes used for dependency injection.

Where is Interface used?

  • In real-time projects :- for layers like service ,repository ... etc.
  • In frameworks like Spring, hibernate(e.g JpaRepository, ApplicationContext ..etc
  • In callbacks/event handling (Gui, Threads)
  • In API design: to define method contracts.

How does Interface work?

  • A class implements an interface using implements keyword.
  • The class must to implement(override all methods) for all abstract methods in the interface.

Which types of Interfaces are in Java?

  • Normal Interface - with abstract,default,static methods.
  • Functional Interface -only one abstract method(e.g, Runnable ,Comparable).
  • marker Interface - no methods ,only used to mark like tags (e.g, serializable ,Cloneable)

(we will see interface types upcoming blogs)

Why Interface provides 100% Abstraction (before Java 8)
Interface Rules:-

  • Methods -> By default ,abstract and public
  • variable -> By default , public , static and final.
  • Can not use constructor , instance variable, can not create object
  • class extend one class but class can implements multiple interface(multilevel inheritance)
  • interface extend another interface

In interface implicitly abstract(incomplete method only-No body), you do not need to use abstract keyword when declaring in the interface.
Let see detail information.

1. Abstract method:-

interface Human{
void  eat(); //implicitely public and abstract,you do not nee to mention public abstract.
public abstract void eat(); // same as above

2.Default methods( introduced in java 8)

interface Human{
//  you must to explicit declare the default
// not abstract method
default void  eat()
{
System.out.println("humans are eat veg and non-veg");
} 
//do not define
default void eat(); // not valid 


}

3.static methods(from java 8)
// explicitly declared static
// not abstract.
interface Human{
static void  eat()
{
System.out.println("humans are eat veg and non-veg");
}

4.Private method(java 9+)
// must to declare private
//not abstract method
interface Human{
private void  eat()
{
System.out.println("humans are eat veg and non-veg");
}

4. final in method

Not allowed in interface in final , final mean can not override , interface the main goal is override/implement  to from interface to implemented class . final keyword  can not to use method like abstract, default...etc. Only abstract, default, static, private (from Java 9+) are allowed

//NOW SEE Variables

interface Fruits
{
String fruitName = "Mango";

//above equal to below
public static final String fruitName = "Mango";
}

// you can not declare in interface:-

- private,protected variable not allowed.
- non-static variable(instance field) and method(with body)   not allowed , because you can not create object in interface. 
- protected (only accessible for within  package or subclass,  not for globally) not to allowed to use in interface method,interface method  must to be  access globally   mean like public contract, so protected not to allowed method and variable.
- one more recap , you can not use in  some access  and non access modifier like protected and final and in the method. 




q.1 can we change value of interface variable?
NO, because , by default set final like constant ,can not change the value.
Enter fullscreen mode Exit fullscreen mode

java 7 and before:

An interface only contain:
abstract methods.
Constant(public static final)
This means 100% abstraction- no method in a body

java8 and later:

  • java 8 introduced:
  • default method(with method body)
  • static methods(with method body)

  • so interface now included concrete method ,so interface not anymore 100% abstraction, like abstract classes(Not 100% abstraction)

  • Supports default and static methods.

java 9

you can write private methods inside of interface.

Key points:-

  • Interface and inside of method(in-completed method) is implicitly abstract , you do not need mention.
  • Interface not to allowed to create object.
  • Interface does not contain any constructor.

  • Interface methods are by default abstract and public

- class can extend only one class. Class can implements more than one interface at a time with (,). interface extends more then one interface.

  • Interface attributes(fields or variable) are by default public, static and final => constant

  • Abstract class can implement interface methods

  • interface can not implement or extend a abstract class or normal class.

  • All fields in a interface are public, static, and final by default.

  • All methods in an interface are public and abstract by default (except default, static, and private methods)

.
Rules for overriding methods from interface:-

  1. Method Signature Must Match
  • method name, parameter list , return type must match
  • you can return same type or sub type(covariant return)
interface Parent {
    Number getMoney(); // return type is Number
}

class Child implements Parent {
    public Integer getMoney() { // Integer is a subtype of Number 
        return 1000;
    }
}


Enter fullscreen mode Exit fullscreen mode

2.Checked Exceptions(must to handle ,you can not ignore) Must Be Compatible(only throw same or child exception not unrelated exception):

Interface method throws a checked exception (must be handled, cannot ignore).
When a class overrides that method, it can:

  • Throw the same exception
  • Throw a subclass of that exception
  • Throw nothing (no exception)
  • But cannot throw a new or unrelated checked exception.
we will see example in Exception handling
Enter fullscreen mode Exit fullscreen mode
  1. Implementation Class Can Be Abstract

If class implemets a interface but does not override the abstract method , you can set abstract keyword in class.

Example:-

interface GrandParent {
    void skill();
}

abstract class Parent implements GrandParent {
    // no implementation of skill() — that's okay because Parent is abstract
}

class Child extends Parent  {
    public void skill() {
        System.out.println("Child implemented method");
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.