Tuesday, February 11, 2014

The Data Access Object (DAO) Design Pattern

In this post, we'll see the basic of DAO Design Pattern, how to implement and what advantages it provide and it's use.


Suppose you are at Disney land with your family or friends and you decide to take a ride on carousel. You see a big panel with so many buttons for operating the carousel.You ask the operator to start the carousel, adjusts it speed and stop it. The operator who know how to use panel, follows your instructions. He is providing you abstraction from the complicated operating panel. In fact, if you go to different carousel in other fair, you can instruct its operartor in the same way and the operator will follow your instructions in the same way even thought his panel is different from that of the first carousel. In essence, you and your family enjoy can take a ride on any carousel without understanding its operating panel because the knowledge to operate the machine is abstracted by the operator.
The Data Access Object pattern provide you abstraction in the same as carousel operator does in providing to their customers.






















In real-life projects, you will encounter situation in which you want to make your data persist. You might use flat files, XML files, RDBMS etc. In such situations, you can use DAO design pattern. This design pattern abstract the details of the underlying persistence mechanism whether you use mysql or oracle and offers you an easy-to-use interface for implementing the storing the data. The DAO pattern hides the implementation detail of the data source from its clients, thereby introducing loose coupling between your core business logs and your storage mechanism.
This will help you to move from one type store to another storage mechanism.

Let’s examine the structure of the pattern.


Apart from the above classes (Client, DAO, TransferObject and DataSource), there could be one more class for this pattern - DAOFactory. You may have multiple DAO object corresponding to different types of objects you want to store such as XML, MYSQL, ORACLE. This factory will define one method for each DAO object.

Let's see with the help of example what we have studied above. In this Paint example, we have a circle class that you want to store in persistance data store. For this we'll create a CircleTransfer object with setter and getter methods.
/*  
  * Transfer Object as per diagram  
  */  
 public class CircleTransfer{  
      private int x;  
      private int y;  
      private int radius;  
      void setX(int x){  
           this.x=x;  
      }  
      void setY(int y){  
           this.y=y;  
      }  
      int getX(){  
           return x;  
      }  
      int getY(){  
           return y;  
      }  
      void setRadius(int radius){  
           this.radius=radius;  
      }  
      int getRadius(){  
           return radius;  
      }  
 }  
 /*  
  * DAO as per Diagram  
  */  
 interface CircleDAO{  
      public void insertCircle(CircleTransfer circle);  
      public CircleTransfer findCircle(int x,int y);  
      public void deleteCircle(int x,int y);  
 }  
 /**  
  * DataSource as per Diagram  
  * Oracle Implementation  
  */  
 public class RDMSDAO implements CircleDAO{  
      @Override  
      public void insertCircle(CircleTransfer circle) {  
           // insertCircle implementation as per Oracle database  
      }  
      @Override  
      public CircleTransfer findCircle(int x, int y) {  
           // findCircle implementation  
           return null;  
      }  
      @Override  
      public void deleteCircle(int x, int y) {  
           // deleteCircle implemenation  
      }  
 }  
 /**  
  * DataSource as per Diagram  
  * MySql Implementation  
  */  
 public class MYSQLDAO implements CircleDAO{  
      @Override  
      public void insertCircle(CircleTransfer circle) {  
           // insertCircle implementation as per MYSQL database  
      }  
      @Override  
      public CircleTransfer findCircle(int x, int y) {  
           // findCircle implementation  
           return null;  
      }  
      @Override  
      public void deleteCircle(int x, int y) {  
           // deleteCircle implemenation  
      }       
 }  
 /*  
  * Factory   
  */  
 public class DAOFactory{  
      public static CircleDAO getCircleDao(String sourceType){  
           switch(sourceType){  
           case "Oracle":  
                return new RDMSDAO();  
           case "mysql":  
                return new MYSQLDAO();  
           }  
           return null;  
      }  
 }  
 /*  
  * Core Business logic  
  */  
 public class Circle{  
      private int x,y,r;  
      Circle(int x,int y, int r){  
           this.x=x;  
           this.y=y;  
           this.r=r;  
      }  
      public CircleTransfer getCircleTransferObject(){  
           CircleTransfer c = new CircleTransfer();  
           c.setRadius(r);  
           c.setX(x);  
           c.setY(y);  
           return c;  
      }  
 }  
 /*  
  * Client  
  */  
 public class DaoPatternDemo {  
      public static void main(String[] javalatte) {  
           Circle c = new Circle(2,2,4);  
           CircleTransfer ct = c.getCircleTransferObject();  
           CircleDAO cDao = DAOFactory.getCircleDao("oracle");  
           cDao.insertCircle(ct);  
      }  
 }  
The Circle class belongs to your core business logic, the Circle class contains a method—getCircleTransferObject()—that returns the CircleTransfer object with the required data.
You define the CircleDAO interface with three methods commonly used with data sources.
The RDBMSDAO implements CircleDAO with a concrete implementation to access the RDBMS data source.
The CircleTransfer object plays a data carrier role between the main() method (which is acting as a Client) and DAO implementation (i.e., the RDBMSDAO class).

Here are the benefits of the DAO design pattern:
  • The pattern introduces an abstraction: the DAO hides the implementation details of the actual data source from the core business logic. The business logic need not know about the nitty-gritty of the data source, which results in easy-to-understand, less complicated code.
  • The pattern separates the persistence mechanism from rest of the application code and puts it together in one class specific to one data source. This centralization enables easier maintenance and easier bug-tracing.
  • It is quite easy to extend support for other data sources using this pattern. For instance, if you want to provide support for the XML-based repository in the FunPaint application, this can be achieved by defining a new class (say XMLDAO). This new class will implement your CircleDAO interface, such that you do not need to change the way you access the data source. The only thing that needs to be changed is the parameter you pass to DAOFactory to create a DAO.



If you know anyone who has started learning Java, why not help them out! Just share this post with them. 
Thanks for studying today!...

Thursday, February 6, 2014

Functional interface and Lambda in Java 8

In this post, we'll see what is a functional interface in Java 8, what its use in Lambda expression and how Lambda expression is useful with detailed examples. Before that you should have an idea of static and default method in interface.

Runnable is one of the interface that we discussed in this post is used by every java programmer. What is so special in Runnable interface is that it has only one abstract method declared in their interface definition. Such interface of this type are ActionListener, Callable and Comparator.

public interface ActionListener extends EventListener {  
      public void actionPerformed(ActionEvent e);  
 }  
 public interface Callable<V> {  
      V call();  
 }  
 public interface Runnable {  
      void run();  
 } 

These interfaces are also called Single Abstract Method interfaces (SAM Interfaces).
Most of the time we use such interface by creating Anonymous inner classes. For example:

class RunnableInterfaceDemo{  
      public static void main(String javalatte[]){  
           new Thread(new Runnable(){  
                @Override  
                public void run() {  
                     System.out.println("Run method.");  
                }  
           }  
           ).start();  
      }  
 } 


import java.awt.BorderLayout;  
 import java.awt.event.ActionEvent;  
 import java.awt.event.ActionListener;  
 import javax.swing.JButton;  
 import javax.swing.JFrame;  
 class TwoInterfaceDemo{  
      public static void main(String javalatte[]){  
           JButton testButton = new JButton("Test Button");  
           testButton.addActionListener(new ActionListener(){  
                @Override  
                public void actionPerformed(ActionEvent e) {  
                     System.out.println("Click is detected");                      
                }  
           });  
              JFrame frame = new JFrame("Listener Test");  
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
              frame.add(testButton, BorderLayout.CENTER);  
              frame.pack();  
              frame.setVisible(true);  
      }  
 } 


Functional Interface

"An interface is considered a functional interface if it contains one and only one abstract method with no default implementation".
Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. 
If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.
Example : java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator, java.util.concurrent.Callable.
Such functional interfaces are leveraged for use with lambda expressions.

public interface Comparator<T>
is also a functional interface but question is that it declared two abstract method but why it is still function interface? one of these equals() which has signature equal to public method in Object class.
As per definition, "If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere."

Lambda (λ) motivation

In mathematics, Computable functions are a fundamental concept within computer science and mathematics. The λ-calculus provides a simple semantics for computation, enabling properties of computation to be studied formally.
Computable functions are used to discuss computability without referring to any concrete model of computation.

One first simplification is that the λ-calculus treats functions "anonymously", without giving them explicit names.
For example, the function
             sqsum(x,y) = x*x + y*y
can be rewritten in anonymous form as
             (x,y) -> x*x +y*y;

Similarly, id(x) = x can be rewritten in anonymous form as x -> x

The second simplification is that the λ-calculus only uses functions of a single input. An ordinary function that requires two inputs, for instance the function, can be reworked into an equivalent function that accepts a single input, and as output returns another function, that in turn accepts a single input. For example
              sqsum(x,y) = x*x + y*y
can be reworked into
              x -> (y->x*x + y*y)

The lambda calculus consists of a language of lambda terms, which is defined by a certain formal syntax, and a set of transformation rules, which allow manipulation of the lambda terms.
As described above, all functions in the lambda calculus are anonymous functions, having no names. They only accept one input variable, with currying used to implement functions with several variables.

These are motivation behind using Lambda in Java 8 for anonymous inner classes.
Lambda expressions address the bulkiness of anonymous inner classes by converting lines of code into a single statement. This simple horizontal solution solves the "vertical problem" presented by inner classes.


Lambda Syntax in java

A lambda expression is composed of three parts.


Argument ListArrow TokenBody
(int x, int y)->x + y


The body can be either a single expression or a statement block. 
In the expression form, the body is simply evaluated and returned. 
In the block form, the body is evaluated like a method body and a return statement returns control to the caller of the anonymous method. 
The break and continue keywords are illegal at the top level, but are permitted within loops. If the body produces a result, every control path must return something or throw an exception.

Example:
(int a, int y) -> x*x + y*y : sum of square of x and y
(String str) -> { System.out.println("Welcome to Lambda Expression " + str); }


Type of Lambda expression

As functional interfaces are leveraged for use with lambda expressions. So basically is an instance of functional interface. As you see, lambda expression itself does not contain any information about which functional interface is implementing that information can been seen from the context in which we use lambda expression.
For instance,
(x,y) -> x*x + y*y
can be instance of the functional interface

interface sqsum{
  int sumsquare(int a, int b);
}
So you can write,
sqsum sm = (x,y) -> x*x + y*y

The data type that these methods expect is called the target type and can be compatible with different functional interfaces, so it use the same lambda expression. 
To determine the type of a lambda expression, the Java compiler uses the target type of the context or situation in which the lambda expression was found. It follows that you can only use lambda expressions in situations in which the Java compiler can determine a target type.
  1. Variable declarations
  2. Assignments
  3. Return statements
  4. Array initializers
  5. Method or constructor arguments
  6. Lambda expression bodies
  7. Conditional expressions, ?:
  8. Cast expressions

For example,

interface floatsqsum{
  float sumsquare(float a, int float);
}

This interface can be used with the previous lambda expression, so it can be written as
floatsqsum sm = (x,y) -> x*x + y*y


How to invoke lambda-expression in Java


  • Via functional interface
  • Functional interface – interface with one method
  • Invoke lambda-expression means to instantiate functional interface
  • Functional interface example:
    interface Runnable { void run(); }
  • Example of lambda-expression invoking
    Runnable r = () -> { System.out.println("hello"); };
    Thread t = new Thread (r);
    t.start();

Examples

Now it's time for example, these example are executed on Java(TM) SE Runtime Environment (build 1.8.0-b128) 
Example 1 : Math operation
In this example, we take one interface with one abstract method that we call functional interface now.

interface IntegerMath{  
      int operation(int a,int b);  
 }  
 public class LambdaDemo {  
      public static void main(String[] javalatteLambda) {  
           IntegerMath addition = (a,b)-> a+b;  
           IntegerMath sub = (a,b)-> a-b;  
           IntegerMath multi = (a,b) -> a*a +b*b;  
           System.out.println("Sub lambda : "+ addition.operation(4, 4));  
           System.out.println("Add lambda :"+ sub.operation(10, 4));  
           System.out.println("Multiply lambda :"+ multi.operation(10, 4));  
      }  
 } 
Output : Sub lambda : 8
Add lambda :6
Multiply lambda :116

Example 2 : Runnable interface
I hope you know that runnable interface is functional interface, so we use this in Lambda expression and we how it reduce the code from 5 lines to 1 line.
public class LambdaRunnableDemo {  
      public static void main(String[] javalatteLambda) {  
           // Anonymous   
           Runnable r1 = new Runnable(){  
                @Override  
                public void run() {  
                     System.out.println("Hello normal runnable interface");  
                }                 
           };  
           //Lambda Runnable  
           Runnable r2 = () -> System.out.println("Hello Lambda runnable interface");  
           r1.run();  
           r2.run();  
      }  
 }  
Output:
Hello normal runnable interface
Hello Lambda runnable interface


Example 3 : Comparator interface
Comparator interface abstract method look like
compare(T o1, T o2) : Compares its two arguments for order.
In this example, we'll sort a person class according to the name of the person using Anonymous class and lambda expression.

import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.Comparator;  
 import java.util.List;  
 class person{  
      private String name;  
      private int age;  
      person(String name,int age){  
           this.name=name;  
           this.age=age;  
      }  
      String getName(){  
           return name;  
      }  
      int getAge(){  
           return age;  
      }  
 }  
 public class LambdaComparatorDemo {  
      public static void main(String[] javalatteLambda) {  
           List<person> list = new ArrayList<person>();  
           list.add(new person("Pardeep",29));  
           list.add(new person("Ravi",34));  
           list.add(new person("Robert",20));  
           list.add(new person("Smith",34));  
           list.add(new person("Agtha",23));  
           //we'll sort person class with normal comparator and lambda expresion  
           Collections.sort(list, new Comparator<person>() {  
                @Override  
                public int compare(person p1, person p2) {  
                     // Asc order  
                     return p1.getName().compareTo(p2.getName());  
                }  
           });  
           System.out.println("====Sorted Asc order====");  
           for(person p : list){  
                System.out.println(p.getName());  
           }  
           // Lambda expression  
           Collections.sort(list, (person p1, person p2)-> p1.getName().compareTo(p2.getName()) );   
           System.out.println("====Lambda Sorted Asc order====");  
           for(person p : list){  
                System.out.println(p.getName());  
           }  
      }  
 }  
Output
====Sorted Asc order====
Agtha
Pardeep
Ravi
Robert
Smith
====Lambda Sorted Asc order====
Agtha
Pardeep
Ravi
Robert
Smith

Lambda expression part 2


If you know anyone who has started learning Java, why not help them out! Just share this post with them. 
Thanks for studying today!...

Friday, January 31, 2014

Abstract Classes vs Interfaces in Java

Abstract Classes vs Interfaces in Java
Everybody knows that in abstract class we can define method body but not in interface, but there are more difference between abstract class and interface. For instance, now in Java 8 we can have default as well as static method in interface. In this post, we look in the difference between them as well as from Java 8 perspective and also the basic knowledge when to use abstract and interface.



   Abstract Classes Interfaces
Keyword(s) used Use the abstract and class keywords to define a class Use the interface keyword to define an
interface.
Keyword used by the
implementing class
Use the extends keyword to inherit from an abstract class Use the implements keyword to implement an
interface.
Default implementation An abstract class can provide default implementation of methods You cannot define methods in an interface; you
can only declare them.
Fields An abstract class can have static and non-static members You cannot have any instance variables
in an interface
Constants An abstract class can have both static (using static and final keyword) and non-static (using final keyword) constants declarations Interfaces can contain constant declarations If you
declare a field, it must be initialized. All fields are implicitly considered to be declared as public
static and final.
Constructors You can define a constructor in an abstract class (which is useful for initializing fields, for example). You cannot declare/define a constructor in an
interface.
Access specifiers You can have private and protected
members in an abstract class.
You cannot have any private or protected members
in an interface; all members are public by default.
Single vs. multiple
inheritance
A class can inherit only one class (which can be either an abstract or a concrete class). A class can implement any number of interfaces.
is-a relationship vs.
following a protocol
An abstract base class provides a protocol; in addition, it serves as a base class in an is-a relationship. An interface provides only a protocol.
It specifies functionality that must be
implemented by the classes implementing it
Default implementation
of a method
An abstract class can provide a default
implementation of a method. So, derived
class(es) can just use that definition and
need not define that method
An interface can only declare a method. All
classes implementing the interface must
define that method.
Difficulty in making changes It is possible to make changes to the implementation of an abstract class. For
example, you can add a method with default implementation and the existing derived classes will not break.
If there are already many classes implementing
an interface, you cannot easily change that
interface. For example, if you declare a new
method, all the classes implementing that
interface will stop compiling since they do not
define that method but it is possible with default method of Java 8

Java 8 update : Interface now contain default and static methods. 

Choosing Between an Abstract Class and an Interface

  • If you are identifying a base class that abstracts common functionality from a set of related classes, you should use an abstract class. If you are providing common method(s) or protocol(s) that can be implemented even by unrelated classes, this is best done with an interface.
  • If you want to capture the similarities among the classes (even unrelated) without forcing a class relationship, you should use interfaces. On the other hand, if there exists an is-a relationship between the classes and the new entity, you should declare the new entity as an abstract class.


Consider using abstract classes if any of these statements apply to your situation:
  • You want to share code among several closely related classes.
  • You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  • You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

Consider using interfaces if any of these statements apply to your situation:
  • You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
  • You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
  • You want to take advantage of multiple inheritance of type.

JDK example:
An example of an abstract class in the JDK is AbstractMap, which is part of the Collections Framework. Its subclasses (which include HashMap, TreeMap, and ConcurrentHashMap) share many methods (including get, put, isEmpty, containsKey, and containsValue) that AbstractMap defines.

An example of a class in the JDK that implements several interfaces is HashMap, which implements the interfaces Serializable, Cloneable, and Map<K, V>. By reading this list of interfaces, you can infer that an instance of HashMap (regardless of the developer or company who implemented the class) can be cloned, is serializable (which means that it can be converted into a byte stream; see the section Serializable Objects), and has the functionality of a map. In addition, the Map<K, V> interface has been enhanced with many default methods such as merge and forEach that older classes that have implemented this interface do not have to define.

Example :
Let’s look at an example of choosing between abstract classes and interfaces in the Paint application. You can have Shape as an abstract base class for all shapes (like Circle, Square, etc.); this is an example of an is-a relationship. Also, common implementations, such as parent shape , can be placed in Shape. Hence, Shape as an abstract class is the best choice in this case.

In Paint, the user can perform various actions on shape objects. For example, a few shapes can be rotated, and a few can be rolled. A shape like Square can be rotated and a shape like Circle can be rolled. So, it does not make sense to have rotate() or roll() in the Shape abstract class. The implementation of rotate() or roll() differs with the specific shape, so default implementation could not be provided. In this case, it is best to use interfaces rather than an abstract class.




If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Everything about Interface in java

In this post, we will see what is an Interface, how to declare it and how to use polymorphically. We will also see new updates about interface in Java 8 and why Java developers have introduced method body in interface in Java 8? Moreover, What will be the use of method body in interface?


Interface
General definition: an interface refers to a common boundary or interconnection between two entities.
For instance, a keyboard in a computer system provides an interface between a human being and the computer. A natural language such as English is an interface between two humans that allows them to exchange their views.

Java definition: Interfaces are like a  100-percent abstract superclass that defines the methods a subclass must support, but not how they must be supported.

In Java, an interface is a set of abstract methods that defines a protocol (i.e., a contract for conduct). Classes that implement an interface must implement the methods specified in the interface. 
An interface defines a protocol, and a class implementing the interface honors the protocol. In other words, an interface promises a certain functionality o its clients by defining an abstraction. All the classes implementing the interface provide their own implementations for the promised functionality.

In other words, an Animal interface might declare that all Animal implementation classes have an eat() method, but the Animal interface doesn't supply any logic for the eat() method. That means it's up to the classes that implement the Animal interface to define the actual code for how that particular Animal type behaves when its eat() method is invoked.

interface Animal{  
      void eat();  
      abstract void walk();  
 }  
 class Lion implements Animal {  
      @Override  
      public void eat() {  
           System.out.println("lion eating");  
      }  
      @Override  
      public void walk() {  
           System.out.println("lion running fast");  
      }  
 }  
 public class AnimalInterfaceDemo{  
      public static void main(String javalatte[]){  
           Lion l = new Lion();  
           l.walk();  
           l.eat();  
      }  
 } 


Example :


public interface Comparable{  
 public int compareTo(Object o);  
 // Intent is to compare this object with the specified object  
 // The return type is integer. Returns negative,  
 // zero or a positive value when this object is less than,  
 // equal to, or greater than the specified object  
 } 

Unrelated classes can provide their own implementations when they implement Comparable. These unrelated classes have one aspect in common: they all follow the specification given by Comparable, and it is left to the implementation of these individual classes to implement compareTo() accordingly.

Conceptually, a class and an interface are two different constructs used for two different purposes. A class combines the state and the behavior of a real object, whereas an interface specifies the behavior of an abstract entity.

How to declare interface
When you create an interface, you're defining a contract for what a class can do, without saying anything about how the class will do it. An interface is a contract.
Interfaces can be implemented by any class, from any inheritance tree. This lets you take radically different classes and give them a common characteristic.
Think of an interface as a 100-percent abstract class. Like an abstract class,an interface defines abstract methods that take the following form:
     abstract void bounce();
But while an abstract class can define both abstract and non-abstract methods, an interface can have only abstract methods.

Some point to remember about interface
  • An interface cannot be instantiated.
  • All interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract.
    public abstract interface Rollable { }
    public interface Rollable { }

    Both of these declarations are legal, and functionally identical.
  • All variables defined in an interface must be public, static, and final—in other words, interfaces can declare only constants (means public static final) , not instance variables.
  • Interface methods must not be static.
  • Because interface methods are abstract, they cannot be marked final, strictfp, or native
  • An interface can extend one or more other interfaces.
  • An interface cannot extend anything but another interface.
  • An interface cannot implement another interface or class.
  • An interface must be declared with the keyword interface.
  • Interface types can be used polymorphically
  • An interface can be declared within another interface or class; such interfaces are known as nested interfaces.
You must remember that all interface methods are public and abstract regardless of what you see in the interface definition.


How to declare interface constants(means public static final)
You're allowed to put constants(means public static final) in an interface. By doing so, you guarantee that any class implementing the interface will have access to the same constant.
By placing the constants right in the interface, any class that implements the interface has direct access to the constants, just as if the class had inherited them.
You need to remember one key rule for interface constants. They must always be
public static final

interface constants{  
      int MAX = 10;  
      public static final int MIN = 2;  
 }  
 public class InterfaceConstant implements constants{  
      public static void main(String javalatte[]){  
           System.out.println("MIN = "+MIN+" MAX = "+MAX);  
      }  
 } 

You can't change the value of a constant!(means public static final declared variable) 

How Interface types can be used polymorphically
Let's say we have class Duck who can swim and quack. Whatever duck class extend this class, they have the functionality of swim and quack.
It looks like

class Duck{  
      public void swim(){  
           System.out.println("I'm swiming");  
      }  
      public void quack(){  
           System.out.println("quacking......");  
      }  
 }  
 class MallardDuck extends Duck{  
      // it has both functionality of swim and qauck  
 }  
 class RedHeadDuck extends Duck{  
      // it has both functionality of swim and qauck  
 }

Now suppose later, we want the fly functionality as per OO we simply add fly() method in the duck class and then all the ducks will inherit it.

class Duck{  
      public void swim(){  
           System.out.println("I'm swiming");  
      }  
      public void quack(){  
           System.out.println("quacking......");  
      }  
      public void fly(){  
           System.out.println("flying.....");  
      }  
 }

By adding the fly behavior in the superclass can't not be appropriate for some Duck subclassess. For instance, RubberDuck extends Duck class.

class RubberDuck extends Duck{  
      public void quack(){  
           System.out.println("squeak......");  
      }  
      //It can't fly  
 }

It will become worse of WoodDuck extends Duck class as it can't fly and swim.
In this case, the use of inheritance for the purpose of reuse hasn't turned out so well when it comes to maintenance.

Now we take the fly() out of the Duck superclass and make a Flyable interface with a fly method. That way, only the ducks that are supposed to fly will implements that interface and have a fly method.
This is one of the design principle : Identify the aspects of your application that vary and separate them from what stays the same.

A reference variable can be declared as a class type or an interface type. If the variable is declared as an interface type, it can reference any object of any class that implements the interface.

class Duck{  
      public void swim(){  
           System.out.println("I'm swiming");  
      }  
      public void quack(){  
           System.out.println("quacking......");  
      }  
 }  
 interface Flyable {  
      void fly();  
 }  
 class RubberDuck extends Duck{  
      public void quack(){  
           System.out.println("squeak......");  
      }  
 }  
 class MallardDuck extends Duck implements Flyable{  
      @Override  
      public void fly() {  
           System.out.println("MallardDuck flying");  
      }  
 }  
 class RedHeadDuck extends Duck implements Flyable{  
      @Override  
      public void fly() {  
           System.out.println("RedHeadDuck flying");  
      }  
 }  
 public class PolymorphicallyInterfaceDemo {  
      public static void main(String javalattep[]){  
           Flyable f = new RedHeadDuck();  
           f.fly();  
           f = new MallardDuck();  
           f.fly();  
           RedHeadDuck r = new RedHeadDuck();  
           r.fly();  
      }  
 }


Q. What will happen if class implement two interface having common method?
Ans:
That would not be a problem as both are specifying the contract that implement class has to follow.
If class C implement interface A & interface B then Class C thing I need to implement print() because of interface A then again Class think I need to implement print() again because of interface B, it sees that there is already a method called test() implemented so it's satisfied.

interface A{  
      void print();  
 }  
 interface B{  
      void print();  
 }  
 class C implements A,B{  
      @Override  
      public void print() {  
           System.out.println("java-latte.blogspot.in");  
      }  
 }  
 public class TwoInterfaceDemo {  
      public static void main(String javalatte[]){  
           C c = new C();  
           c.print();  
      }  
 }  


Most of the time we'll think why interface has no body and what if it has body what will be merits and demerits that we'll see in the next section as per draft version of Java 8.

The Interface Body in Java 8
The interface body can contain abstract methods, constants variabledefault methods, and static methods. An abstract method within an interface is followed by a semicolon, but no braces (an abstract method does not contain an implementation). 
Default methods are defined with the default modifier, and static methods with the static keyword. All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.

In addition, an interface can contain constant(means public static final) declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, you can omit these modifiers.


Drawback of interface
Consider an interface that you have developed called Animal:

public interface Animal {  
   void eat();  
   int weight(String s);  
 }

Suppose that, at a later time, you want to add a third method to Animal, so that the interface now becomes:

public interface Animal {  
   void eat();  
   int weight(String s);  
   void swim();  
 }

If you make this change, then all classes that implement the old Animal interface will break because they no longer implement the old interface. Programmers relying on this interface will protest loudly

Default method in interface

If you want to add additional methods to an interface, you have several options.
You could create a AnimalSwim interface that extends Animal:

public interface AnimalSwim extends Animal {  
   boolean swim();    
 } 

Now users of your code can choose to continue to use the old interface or to upgrade to the new interface.

Alternatively, you can define your new methods as default methods. The following example defines a default method named swim:

public interface Animal {  
   void eat();  
   int weight(String s);  
   default void swim() {  
     // Method body   
   }  
 }

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.

  • You specify that a method definition in an interface is a default method with the default keyword at the beginning of the method signature. 
  • All method declarations in an interface, including default methods, are implicitly public, so you can omit the public modifier.

Extending Interfaces That Contain Default Methods
When you extend an interface that contains a default method, you can do the following:
  • Don't mention the default method,and lets your extend interface inherit the default method.
  • You can redeclare the default method which make them abstract again. Similary, when abstract class extend abstract class.
  • You can redefine the default method similar to overriding.

QAgain one question come to mind that if two interface are providing default method with similar signatures and class is extending both the interface, will it not be again diamond problem?
Yes, you are thinking right but Java doesn't allow you to implement interface with has same default method.

Static Methods in interface
In addition to default methods, you can define static methods in interfaces
A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.
This makes it easier for you to organize helper methods in your libraries; you can keep static methods specific to an interface in the same interface rather than in a separate class.

interface stack{  
      void push(int i);  
      int pop();  
      int peek();  
      static calculateElement(StackImp st){  
           // code to calculate the no of element in stack  
      }  
 }


Like static methods in classes, you specify that a method definition in an interface is a static method with the static keyword at the beginning of the method signature. All method declarations in an interface, including static methods, are implicitly public, so you can omit the public modifier.

Interface in Java 9(update)
As you seen earlier, you can define abstract methodsconstants variabledefault methods, and static methods in java 8. Now with Java 9, you can define private methods and private static methods 
Question arise, why private methods? As you can define default functionality in defaults methods that will be available to all the class who implements the interface. In static methods, we write some helper method so that it specific to interface. However, when we need to define some common functionality that is only specific to interface and no class can inherit that such as connection to logging,opening a file etc. so that it can be only used inside interface. That means no duplicate code and we can control what we want to expose to the client.


In order to write private method in interface, just use private identifier and must write the body




If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...