☰ Topics

Interface

Interface is 100% incomplete situation (where only signature is given) i.e. it has non-concrete functions. Definition of the functions will be given by implements class. For eg: Event handling is a type of interface because when an event is created, then what that event will perform is defined by the end user programmer. Here there can be few functions whose definition as well as signatur will be given in rest will be empty, which will be overriden in implements class. It is the blueprint of class same as original. Interface looks like class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body). Also, the variables declared in an interface are public, static, final by default.

There are two methods of creating a thread i.e. either by extending Thread class or by implementing runnable interface. As we know java does not support multiple inheritance but there are certain situations where members of more than one classes are required. In that case interfaces are useful because more than one interface can be implemented by a class. We can say that, interface is the solution for multiple inheritance.

  1. To make interface, we use the interface keyword instead of class.
  2. Instead of extends, we use implements keyword.
  3. Interface are implicitly abstraction that is why we cannot create the object.
  4. Interface variables must be initialized at the time of declaration otherwise compiler will throw error.
  5. A class can implement any no. of interfaces.
  6. If there are two or more same methods in two interfaces and a class implements both interfaces, implementation of the method once is enough.
  7. Variables name conflicts can be resolved by interface name.
  8. If a class includes an interface but does not fully implement the methods defined by that interface then the class must be declared as an abstract.
  9. We cannot instantiate an interface in Java.
  10. It provides complete abstraction as none of its methods can have body(concrete method).
  11. Without bothering about the implementation part, we can achieve the security of implementation.
  12. When u implement an interface method it must be declared as public.
General syntax for defining an interface:-
	  access specifier interface interface-name{
	    return-type method-1(parameter list);
	    return-type method-2(parameter list);
        type final variable = value;
	   }
    
Example:-
interface C1{
    void call();
}
class C2 implements C1{
    public void call(){
        System.out.println("Hello Friends");
    }
    public static void main(String s[]){
        C2 m=new C2();
        m.call();
    }
}

OUTPUT:-
                        
Hello Friends