Skip to main content

Interfaces


Interfaces:
1) Introduction
2) Interface declarations and implementations.
3) Extends vs implements
4) Interface methods
5) Interface variables
6) Interface naming conflicts
        a) Method naming conflicts
        b) Variable naming conflicts
7) Marker interface
8) Adapter class
9) Interface vs abstract class vs concrete class.
10) Difference between interface and abstract class?
11) Conclusions
Definition-1: Any service requirement specification (srs) is called an interface.
Example1: Sun people responsible to define JDBC API and database vendor will provide an implementation for that.
Diagram:
Example2: Sun people define SERVLET API to develop web applications web server vendor is
responsible to provide the implementation. 
Diagram: 
Definition-2: From the client's point of view an interface defines the set of services that his excepting. 
From the service provider point of view, an interface defines the set of services that are offering. Hence an interface is considered as a contract between client and service provider.
Example: ATM GUI screen describes the set of services that bank people offering, at the same time the same GUI screen the set of services what customer his excepting hence this GUI screen acts as a contract between bank and customer.
Definition-3: Inside interface, every method is always abstract whether we are declaring or not hence
the interface is considered as 100% pure abstract class.
Summery def: Any service requirement specification (SRS) or any contract between client and service provider or 100% pure abstract classes is considered as an interface.Declaration and implementation of an interface:
Note1: Whenever we are implementing an interface compulsory for every method of that the interface we should provide implementation otherwise we have to declare the class as abstract in that case child class is responsible to provide an implementation for remaining methods.
Note2: Whenever we are implementing an interface method compulsory it should be declared as public otherwise we will get a compile-time error. 
Example:
interface Interf
    {
         void methodOne();
         void methodTwo();
    } 






class SubServiceProvider extends ServiceProvider { }
Output:
Compile time error.
D:\Java>javac SubServiceProvider.java
SubServiceProvider.java:1: SubServiceProvider is not abstract and does not override abstract method methodTwo() in Interf class SubServiceProvider extends ServiceProvider
Extends vs implements:
• A class can extend only one class at a time.
Example:
       class One 
            {
                 public void methodOne()
                    {
                    }
           }
      class Two extends One{
        }
• A class can implement any no. Of interfaces at a time.  
Example:
           interface One
                   {
                       public void methodOne();
                   }
           interface Two
                 {
                      public void methodTwo();
                  }
           class Three implements One,Two
                 {
                      public void methodOne(){
                 }
           public void methodTwo(){
                 }
           }
• A class can extend a class and can implement an interface simultaneously.
     interface One
                {
                    void methodOne();
                }
      class Two
             {
                     public void methodTwo()
                         {
                         }
              }
       class Three extends Two implements One
              {
                     public void methodOne()
                         {
                          }
               }
• An interface can extend any no. Of interfaces at a time.
Example:
          interface One
                  {
                         void methodOne();
                   }
          interface Two
                  {
                        void methodTwo();
                   }
          interface Three extends One,Two
               {
                } 
1) Which of the following is true? 
1. A class can extend any no. Of classes at a time.
2. An interface can extend only one interface at a time.
3. A class can implement only one interface at a time.
4. A class can extend a class and can implement an interface but not both simultaneously.
5. None of the above.
Ans: 5
2) Consider the expression X extends Y for which of the possibility of X and Y this expression is true?
1. Both x and y should be classes.
2. Both x and y should be interfaces.
3. Both x and y can be classes or can be interfaced.
4. No restriction.
Ans: 3
3) X extends Y, Z?
• X, Y, Z should be interfaced.
4) X extends Y implements Z?
• X, Y should be classes.
• Z should be an interface.
5) X implements Y, Z?
• X should be class.
• Y, Z should be interfaced.
6) X implements Y extend Z? 
Example:
         interface One
             {
              }
          class Two 
              {
               }
          class Three implements One extends Two{
              }
Output:
Compile-time error.
D:\Java>javac Three.java
Three.java:5: '{' expected
class Three implements One extends Two{
Every method present inside an interface is always public and abstract whether we are declaring or not. Hence inside interface the following method declarations are equal.void methodOne(); 
public Void methodOne();
abstract Void methodOne(); Equal
public abstract Void methodOne();
As every interface method is always public and abstract we can’t use the following
modifiers for interface methods.
• Private, protected, final, static, synchronized, native, strictfp. Inside interface which method declarations are valid?
1. public void methodOne(){}
2. private void methodOne();
3. public final void methodOne();
4. public static void methodOne();
5. public abstract void methodOne(); 
Ans: 5  
Interface variables:
• An interface can contain variables to define requirement level constants.
• Every interface variable is always public static and final whether we are declaring or not.
Example:
          interface interf
              {
                   int x=10;
              }
Public: To make it available for every implementation class.
Static: Without an existing object also we have to access this variable.
Final: The implementation class can access this value but cannot modify it.
• Hence inside the interface, the following declarations are equal.
int x=10;
public int x=10;
static int x=10;
final int x=10;                                          Equal
public static int x=10;
public final int x=10;
static final int x=10;
public static final int x=10;
• As every interface variable by default public static final, we can’t declare with the following modifiers.
       • Private
       • Protected 
       • Transient
       • Volatile
• For the interface variables compulsory we should perform initialization at the time of the declaration only otherwise we will get a compile-time error. 
Example:
            interface Interf
                 {
                         int x;
                  }
Output:
Compile time error.
D:\Java>javac Interf.java
Interf.java:3: = expected
int x;
Which of the following declarations are valid inside interface?
1. int x;
2. private int x=10;
3. public volatile int x=10;
4. public transient int x=10;
5. public static final int x=10;
Ans: 5
• Interface variables can be access from implementation class but cannot be modified.
Example:
             interface Interf
                 {
                       int x=10;
                 }
Example 1:
Example 2:
         class Test implements Interf
             {
                  public static void main(String args[])
                      {
                         int x=20;
                        //here we declaring the variable x.
                        System.out.println(x);
                      }
              }
Output:
D:\Java>javac Test.java
D:\Java>java Test
20
Interface naming conflicts:
Method naming conflicts:
Case 1:
If two interfaces contain a method with the same signature and same return type in the implementation class only one method implementation is enough.
Example 1:
           interface Left
              {
                 public void methodOne();
              }
Example 2:
          interface Right
               {
                    public void methodOne();
               }
Example 3:
         class Test implements Left,Right
             {
                   public void methodOne()
                        {
                        }
              }
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java 
Case 2:
• if two interfaces contain a method with the same name but different arguments in the implementation class we have to provide an implementation for both methods and these methods acts as overloaded methods
Example 1:
          interface Left
              {
                      public void methodOne();
               }
Example 2:
             interface Right
                  {
                       public void methodOne(int i);
                   }
Example 3:
               class Test implements Left,Right
                    { 
                            public void methodOne()
                                 {
                                 }
                  public void methodOne(int i)
                     {
                       }
                 }
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
Case 3:
• If two interfaces contain a method with the same signature but different return types then it is not possible to implement both interfaces simultaneously.
Example 1:
           interface Left
               {
                   public void methodOne();
               }
Example 2:
          interface Right 
             { 
                  public int methodOne(int i);
             }
• We can’t write any java class that implements both interfaces simultaneously. Is a java class can implement any no. Of interfaces simultaneously?
• Yes, except if two interfaces contain a method with the same signature but different return types. Variable naming conflicts:
• Two interfaces can contain a variable with the same name and there may be a chance variable naming conflicts but we can resolve variable naming conflicts by using interface names.
Example 1:
           interface Left
                {
                      int x=888;
                 }
Example 2:
            interface Right
               {
                       int x=999;
                }
Example 3:
             class Test implements Left,Right
                 {
                         public static void main(String args[])
                              {
                                     //System.out.println(x);
                                      System.out.println(Left.x);
                                      System.out.println(Right.x);
                             }
                 }
Output:
D:\Java>javac Left.java
D:\Java>javac Right.java
D:\Java>javac Test.java
D:\Java>java Test
888
999 
Marker interface: if an interface doesn’t contain any methods and by implementing that interface if our object gets some ability such type of interfaces are called Marker interface (or) Tag interface (or) Ability interface.
Example:
Serializable
cloneable
RandomAccess                      These are marked for some ability
SingleThreadModel
 .
 .
 .
 .
Example 1: By implementing a Serializable interface we can send that object across the network and we can save the state of an object into a file.
Example 2: By implementing the SingleThreadModel interface Servlet can process only one client request at a time so that we can get “Thread Safety”.
Example 3: By implementing a Cloneable interface our object is in a position to provide exactly duplicate cloned objects.
Without having any methods in marker interface how objects will get the ability?
• Internally JVM will provide the required ability.
Why JVM is providing the required ability?
• To reduce the complexity of the programming.
Is it possible to create our own marker interface?
• Yes, but customization of JVM is required.
Adapter class:
• An adapter class is a simple java class that implements an interface only with empty implementation for every method.
• If we implement an interface directly for each and every method compulsory we should provide implementation whether it is required or not. This approach increases the length of the code and reduces readability.
Example 1:
interface X{
void m1();
void m2();
void m3();
void m4();
 //.
 //.  
 //.
 //.
void m5();
Example 2:
      class Test implements X
           {
                 public void m3()
                    {
                         System.out.println("m3() method is called");
                    }
                      public void m1(){}
                      public void m2(){}
                      public void m4(){}
                      public void m5(){}
            }
• We can resolve this problem by using an adapter class.
• Instead of implementing an interface if we can extend the adapter class we have to provide the implementation only for required methods but not for all methods of that interface.
• This approach decreases the length of the code and improves readability.
Example 1:
       abstract class AdapterX implements X
            {
                  public void m1(){}
                  public void m2(){}
                  public void m3(){}
                  public void m4(){}
                  //.
                  //.
                  //.
       public void m1000(){}
        }
Example 2:
public class Test extend AdapterX
   {{
       public void m3(){
    }}
Example:
• Generic Servlet simply acts as an adapter class for the Servlet interface.
What is the difference between interface, abstract class, and concrete class?
When we should go for the interface, abstract class, and concrete class?
• If we don’t know anything about implementation just we have requirement specification then we should go for an interface.
• If we are talking about implementation but not completely (partial implementation) then we should go for abstract class.
• If we are talking about implementation completely and ready to provide service then we should go for a concrete class.
Example:

What is the difference between an interface and an abstract class? 
We can’t create an object for abstract class but the abstract class can contain constructor what is the need? 
• This constructor will be executed for the initialization of the child objects.
Example:
       class Parent
           {
              Parent()
                 {
                     System.out.println(this.hashCode());
                }
           }
       class child extends Parent
            {
                   child()
                      {
                             System.out.println(this.hashCode());
                      }
             }
       class Test
           {
                public static void main(String args[])
                   {
                        child c=new child();
                        System.out.println(c.hashCode());
                   }
          }
Every method present inside the interface is abstract but in abstract class also we can take only
abstract methods then what is the need for interface concept?
• We can replace the interface concept with an abstract class. But it is not a good programming practice. We are misusing the role of an abstract class.

Comments

Popular posts from this blog

Core Java

Content 1 - Language fundamental   Identifier Reserved words Data types Literals Arrays Types of variables Var arg method Main method Java coding standards 2 -  Declaration and Access Modifiers Java source file structure Class modifiers Member modifiers Interfaces 3 - Exception Handling Introduction Runtime stack mechanism Default exception handling in java Exception hierarchy Customized exception handling by try-catch  Control flow in try-catch Methods to print exception information Try with multiple catch blocks Finally Difference between final, finally, finalize Control flow in try-catch-finally Control flow in nested try-catch-finally Various possible combinations of try-catch-finally throw keyword throws keyword Exception handling keywords summary Various possible compile-time errors in exception handling Customized exceptions Top-10 exceptions  4 - String Concept of String Immutable String String Comparison String Conca