LightBlog

Java - Interfaces

·         We can declare interface by ‘interface’ keyword & implementing using ‘implemets’ keyword. The allowed modifiers for interface are
public
abstract
strictfp
<default>

·         When ever a class implementing an interface we should provide the implementation for all the interface methods. Other wise the class must be declared that class as abstract. Violation leads to compile time error.

·         By default all interface methods are ‘public abstract’ & variables are ‘public static final’.

·         When ever we are implementing an interface method compulsory we should declare that method as public, otherwise we will get compile time error.
interface sample {
    void m1();
}

class Test implements sample {
    void m1() {
    }
}

·         Every interface variable is by default public static and final. Hence the following declarations are equal inside interface.
int i = 10;
public int i = 10;
public static int i = 10;
public static final int i = 10;

·         For interface variables we should perform initialization at the time of Declaration only.
interface inter
{
int i ;  C.E = expected.
}

·         interface variables are by default available in the implemented classes.From the implementation classes we are allowed to access but not allowed to change their values i.e reassignment is not possible because these are final.
interface inter {
    int i = 10;
}

class test implements inter {
    public static void main(String arg[]) { 
            i=20;
            System.out.println(inter.i);
    }
}
B.java:7: error: cannot assign a value to final variable i
                i=20;
                ^



Naming conflicts in interfaces

·         If two interfaces contain a method with same signature and same return type in the implementation class, only one method implementation is enough
interface Left {
    void m1();
}

interface Right {
    void m1();
}

class Test implements Left, Right {
    public void m1() {
            System.out.println("method");
    }
   
    public static void main(String[] args) {
            Left l = new Test();
            l.m1();
           
            Right r = new Test();
            r.m1();
    }
}
method
method


·         If two interfaces contain a method with same signature but different return type then we can’t implement those two interfaces simultaneously.
interface Left {
    void m1();
}

interface Right {
    int m1();
}

class Test implements Left, Right {
    public void m1() {
            System.out.println("void");
    }
   
    public int m1() {
            System.out.println("void");
    }      
}
Test.java:10: error: m1() in Test cannot implement m1() in Right
        public void m1() {
                    ^
  return type void is not compatible with int



Marker Interface

an interface which doen’t contain any methods, treated as ‘Marker’ interface

By implementing an interface if our objects will get some ability, Such type of interfaces are called “marker” or “taginterface”.
Ex: Serializable, Clonable interfaces are marked for some ability.



Interface Enhancements

interface Default Methods: Java 8

Java 8 allows you to add non-abstract methods in interfaces. These methods must be declared default methods.

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
interface Vehicle {
        default void move() {
                System.out.println("Def. move");
        }
}

class Car implements Vehicle {
         
}

class Bus implements Vehicle{
        @Override
        public void move() {
        System.out.println("Bus. Move");
        }
}

public class Test{
        public static void main(String[] args) {
                new Car().move();
                new Bus().move();
        }
}
Def. move
Bus. Move
·         Vehicle interface defines a method move() and provided a default implementation as well. If any class implements this interface then it need not to implement it’s own version of move() method. It can directly call instance.move().
·         If class willingly wants to customize the behavior of move() method then it can provide it’s own custom implementation and override the method by removing ‘default’ keyword


interface Static Methods : Java 8

Java interface static method is similar to default method except that we can’t override them in the implementation classes. This feature helps us in avoiding undesired results incase of poor implementation in implementation classes
interface Vehicle {
        default void move() {
                System.out.println("Def. move");
        }
        static void year(){
                System.out.println("Def. 1998");
        }
}

class Test implements Vehicle{
        @Override
        public void move() {
        System.out.println("Bus. Move");
        }
        static void year(){
                System.out.println("2018");
        }
        public static void main(String[] args) {
                Vehicle.year();
                year();
        }
}
Def. 1998
2018
Note that year() is a simple class method, it’s not overriding the interface method. For example, if we will add @Override annotation to the year() method, it will result in compiler error.


Interface Private Methods – Java 9

private methods will improve code re-usability inside interfaces. Foe example, if two default methods needed to share code, a private interface method would allow them to do so, but without exposing that private method to it’s implementing classes.

Using private methods in interfaces have four rules :
·         Private interface method cannot be abstract.
·         Private method can be used only inside interface.
·         Private static method can be used inside other static and non-static interface methods.
·         Private non-static methods cannot be used inside private static methods.
public interface Calculator
{
    default int addEvenNumbers(int... nums) {
        return add(n -> n % 2 == 0, nums);
    }
 
    default int addOddNumbers(int... nums) {
        return add(n -> n % 2 != 0, nums);
    }
 
    private int add(IntPredicate predicate, int... nums) {
        return IntStream.of(nums)
                .filter(predicate)
                .sum();
    }
}


Functional Interfaces

Functional interfaces are also called Single Abstract Method interfaces (SAM Interfaces). As name suggest, they permit exactly one abstract method inside them. Java 8 introduces an annotation i.e. @FunctionalInterface which can be used for compiler level errors when the interface you have annotated violates the contracts of Functional Interface.

@FunctionalInterface
public interface Test {
    public void firstWork();
}
Please note that a functional interface is valid even if the @FunctionalInterface annotation would be omitted. It is only for informing the compiler to enforce single abstract method inside interface.
Share on Google Plus

About Unknown

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments:

Post a Comment