Hi I understand the usage of interfaces meaning they are meant to reduce coupling and make coding more effecient. Btu could one explaing how to use it and in what situations regarding in what part of the program do you use it at?

Thank s in advance!

Recommended Answers

All 3 Replies

interfaces are used when you dont want your classes to be used directly by another...we put an interface for that classand access that class through the interface..
Ex:
if you want meet the president its not possible to directly approach him ,we need to take an appointment from assistent
here assistent acts as interface ,through that assistent we can approach president..

import java.lang.*;
import java.io.*;
import java.util.*;

interface Jp
{
    final static int passcode=2303;
     abstract void pc();
     abstract void penc();

}

private class Spen implements Jp
{

  void pc(int passcode)
   {
     this.passcode=passcode;
    }

   public void penc()
    {
       System.out.println("ur pen is renolds");
      int a=passcode+10;
    }

     public void displaylocal()
      {
        System.out.println("ur passcode is:"+passcode);
       }
}

class Jpen
 {
      public static void main(String args[])throws IOException
        {

            Spen sp=new Spen();
            sp.pc();

         }
}

here i dont want everyone to use the pen class so i put a interface and gave passcode to access the class
though my exapmle is stupid i hope u understand

they're also used to simulate multiple inheritance, since multiple inheritance is impossible in Java. notice, I said "simulate", since this is not multiple inheritance.
the main differences between extending classes and implementing interfaces:
- you can only extend one class, while you can implement as much interfaces as you want
- you automatically 'get' the code you extend, you don't have to redefine it, unless of course you would like to change the implementation of a method, but you don't inherit any logic from an interface. an interface just tells you what methods you have to implement, not how to implement them.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.