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!

5 Years
Discussion Span
Last Post by elijahStar

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..
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)

   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();


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

Edited by ~s.o.s~: Fixed code tags


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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.