Monday, December 26, 2016

What is a java Interface

Definitions:
An interface is a contract between programmer and programming language. It defines a set of standards which programmer must follow while developing their programs. An interface looks like a class, but it is not a class, because it is not developed to represent an object.

Above is the most suitable definition of the interface, we can define interface in several other ways like:
- Interface is the blue print of a class.
- Interface is created to achieve the abstraction.
- Interface is a medium between programmer and programming language
- Interfaces are used to define standards.

Let’s take a real example - a student has paid some fees in college to take admission in B Tech. So, the contract between them is that, student will pay some amount and in return he will get the knowledge and degree from the college, and proof of this contract is the registration form, which student fills in the college.

Syntax for declaring an interface:

public interface My {

}

Rule - By default the interfaces are abstract, so we cannot create instance / object of interface. All methods declared inside interface are by default abstract and public because these methods are going to be called by others.

There are 2 major uses of inheritance 1) reusability through classes and 2) dynamic binding through interfaces.

Now, to use the functionality of above interface, first we have to implement it in our classes. Like this:

class Child implements My
{
      //definitions of interface methods goes here
}

Quick Question  why technology has preferred to use implements word instead of extends, as we did in class?
Answer – because we extends means increase, but we are not increasing anything here because there is nothing inside the interface, and we always implement the contracts, so technology has chosen the word implements instead of extends.

Rule – while giving the body of a method implemented from an interface, the method should be declared as public always. A child class has to implement all methods of the interface, an abstract class partially implements the abstraction but interface fully supports it.

Enough theory, let’s take some program examples then we will summarize the characteristics of interface.


interface My {

      void show();
}

interface My1
{
      void display();
}

public class MyImpl implements My, My1
{

      public void show() {
            System.out.println("Show method called.");
      }
     
      public void display()
      {
            System.out.println("Display method called.");
      }

      public static void main(String args[])
      {
            My m = new MyImpl();
            m.show();
           
            My1 m1 = new MyImpl();
            m1.display();
      }
}

Output:


Quick Question – What will happen if we declare the show() method in My1 as well?
Answer – this is allowed, because we are just getting method prototype from interfaces and we are providing its definition in our class only once. So, no possibility of ambiguity in this type of multiple inheritance through interface. Now, by doing this both m and m1 objects can call show method.

This relates to a real example of joint account in a bank, where 2 or more members can open a joint account and both are allowed to access the account. So show method is a joint account for both interfaces.

Here is its implementation:

interface My {

      void show();
}

interface My1
{
      void display();
      void show();
}

public class MyImpl implements My, My1
{

      public void show() {
            System.out.println("Show method called.");
      }
     
      public void display()
      {
            System.out.println("Display method called.");
      }

      public static void main(String args[])
      {
            My m = new MyImpl();
            m.show();
           
            My1 m1 = new MyImpl();
            m1.display();
            m1.show();
           
      }
}

Output:





Extending Interfaces:

An interface can extend another interface to inherit its property, in this case we have to use “extends” keyword:

interface My {

      void show();
}

interface My1 extends My
{
      void display();
}

public class MyImpl implements My1
{

      public void show() {
            System.out.println("Show method called.");
      }
     
      public void display()
      {
            System.out.println("Display method called.");
      }

      public static void main(String args[])
      {
            My1 m1 = new MyImpl();
            m1.show();
            m1.display();
      }
}


Output:
Show method called.
Display method called.



Extending multiple interfaces:

An interface can extend multiple interfaces, let’s try:
interface MyMaster1 {

      void showMaster1();
}

interface MyMaster2
{
      void showMaster2();
}

interface MyMaster3 extends MyMaster1, MyMaster2
{
      void showMaster3();
}

public class MyImpl implements MyMaster3
{

      public static void main(String args[])
      {
            MyMaster1 m1 = new MyImpl();
            m1.showMaster1();
            //m1.showMaster2();     Error
            //m1.showMaster3();     Error
           
            MyMaster2 m2 = new MyImpl();
            m2.showMaster2();
           
            MyMaster3 m3 = new MyImpl();
            m3.showMaster3();
           
      }

      @Override
      public void showMaster1() {
            System.out.println("Master 1 executed"); 
      }

      @Override
      public void showMaster2()
      {
            System.out.println("Master 2 executed");
      }

      @Override
      public void showMaster3()
      {
            System.out.println("Master 3 executed");
      }
}

Output:
Master 1 executed
Master 2 executed
Master 3 executed

Before moving to the further concept, let’s discuss the “final in java”:

"final" in java is similar to constants in C/C++. We can declare a class, a method, data members and local variables as final. Let’s discuss all of them one by one:

  • final class – when we declare a class as final then that class cannot be inherited. So, we can use final if we do not want any other classes to extend my class.
Syntax:
final class FinalClassDemo {

}

class FinalClassDemoImpl extends FinalClassDemo
{
     
}

When we compile above code, compiler will give error : “The type FinalClassDemoImpl cannot subclass the final class FinalClassDemo”

  •  final method or member function – when we define a method as a final, it means none of the child classes can override this method. So, when we want to stop method overriding then we should declare a method as final.
class FinalMethodDemo {

            final public void finalMethod()
            {
                  System.out.println("Message from a final method.");
            }
}

class FinalClassDemoImpl extends FinalMethodDemo
{
            final public void finalMethod() //line # 12
            {
                  System.out.println("Message from a final method.");
            }
}

When we will compile above code, compiler will show this error at line number 12  “Cannot override the final method from FinalMethodDemo”

  •  final local variable - when we declare a local variable as final, then it will become a constant, it means no one can change its value once it is declared and initialized.
class Temp
{
      public static void main(String args[])
      {
            final int x = 10;
            System.out.println("x = " + x);
           
            x = x + 10; //Line No 8 - error at this line

            final Temp temp = new Temp();
           
            temp = new Temp(); //Line No 12 - error at this line
           
      }
}

When we try to compile above code compiler will give this error at line no 8 and 12 : “The final local variable temp / x cannot be assigned. It must be blank and not using a compound assignment”

  • final data member – lets discuss about both static and non static data members as final one by one:

a.    static final data member  - when we declare a static data member as final, then we cannot change its value throughout  the program. We must initialize its value, because static data member always initialize with 0 and this value will never be changed.
      class Temp
      {
             final static int x = 10;
             public static void main(String args[])
             {
                  x = x + 10; //Line No 7 - error at this line
                  System.out.println("x = " + x);
             }
}
b.    non static data member – again when we declare a non static data member, we must initialize it with some value, because java always initialize it with 0. But, as we know the instance variables are separate for each objects, so the same initial value for will be available for all objects, the there is no difference between final non static data member and a static data member.
There is a solution of above problem – the solution is, assign values for each objects and then make it final. This concept is called “Blank final variable” it says make a variable final but don’t initialize it with initial zero.

Let’s clarify it with an example:

class Temp
{
      final int x;
      Temp(int x)
      {
            this.x = x;
      }
     
      public static void main(String args[])
      {
            Temp temp1 = new Temp(10);
            System.out.println("temp1.x = " + temp1.x);
           
            Temp temp2 = new Temp(20);
            System.out.println("temp2.x = " + temp2.x);          
      }
}

Output:


In above program, we are easily able to assign separate values for each objects in instance variables. Now, let’s try to change its values like below, it will give compiler error at line no 17 & 18: “The final field Temp.x cannot be assigned”

class Temp
{
      final int x;
      Temp(int x)
      {
            this.x = x;
      }
     
      public static void main(String args[])
      {
            Temp temp1 = new Temp(10);
            System.out.println("temp1.x = " + temp1.x);
           
            Temp temp2 = new Temp(20);
            System.out.println("temp2.x = " + temp2.x);

            temp1.x = 40;     //line no 17
            temp2.x = 50;     //line no 18
           
      }
}

Now, let’s resume back to the interface concept.

Interface data members – all data members are by default final and static.

interface TempInterface
{
      int x = 10; // by default x is final and static
}
class Temp
{
      public static void main(String args[])
      {
            System.out.println("x = " + TempInterface.x);
           
            TempInterface.x = 20; // line no 11      
      }
}

Compiler will complain at line 11 in above program, error: The final field TempInterface.x cannot be assigned.

Now, let’s study a very important factor on interface, let’s run this program first:

interface TempInterface
{
      void show();
}

class TempInterfaceImpl implements TempInterface
{
      public void show()
      {
            System.out.println("Show method executed.");
      }
     
      public void display()
      {
            System.out.println("display method executed.");
      }
     
      public static void main(String args[])
      {
            TempInterface tempInterface = newTempInterfaceImpl();
            tempInterface.display(); //line no 21
      }
}

Compiler will give an error at line number 21 in above program “The method display() is undefined for the type TempInterface” yes obviously it deserves the error. Now, lets try similar program and surprisingly it will run fine, we will then discuss why so:

interface TempInterface
{
      void show();
}

class TempInterfaceImpl implements TempInterface
{
      public void show()
      {
            System.out.println("Show method executed.");
      }
     
      public void display()
      {
            System.out.println("display method executed.");
      }
     
      public String toString()
      {
            return "Hello from dev21century";
      }
     
      public static void main(String args[])
      {
            TempInterface tempInterface = newTempInterfaceImpl();
            //tempInterface.display(); //line no 21 error

            String message = tempInterface.toString();
            System.out.println(message);
      }
}


Output:




Characteristics of Java Interface:
  1. A class can implement more than one interfaces, by this way we can partially achieve multiple inheritance without any issues.
  2. By default all data members of interface are final, public and static.
  3. By default all methods of interface are public and abstract.
  4. By default interface are abstract.
  5. A class implementing interface must give definition of all of its methods.
  6. Dynamic binding or runtime polymorphism can be achieved by interface.
  7. An interface can extend more than one interfaces by using “extends” keyword.

No comments:

Post a Comment