06 August, 2013

Why Interface methods are Public ?


Do you know why methods are Public in Interface ?

/*
 * @Author Manoj
 * Interface with two method
 */

interface IMyInterFace{
    public void display();
    public void calculate();
}



//Implementation Class
class MyImplClass implements IMyInterFace{   
   
   
    //Interface Method
    public void display(){
        System.out.println("Hi: Override-Display");
    }
   
    //private void display(){
    //    System.out.println("Hi: Override-Display with Private");
    //If you run this method then, Error Weaker Access Privileges
    //}
   
    //Interface method
    public void calculate(){
        System.out.println("Hi: Override-calculate");
    }
   
    //Class Method
    public void show(){
        System.out.println("Hi: I am Own Method");
    }
   
    public static void main(String str[]){
        IMyInterFace f=new MyImplClass();
        f.display();
    }
}


Output:- Hi: Override-Display




Explanation :-

In the above example , Interface methods are public means extremely strong access.When , you try to access those public method with private or protected (weak access privilege than public) then, you will face error.So, I override those two interface methods with same strong access privilege (public).
Please know more about strong/weak access privilege.

As you know ,objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world.So, the most common form, an interface is a group of related methods with empty bodies.

When you are creating an Interface, you must have to declare the methods as Public inside the interface.When you are creating an Interface , it means you are creating a common schema/structure and you are going to implement over any class (Known as Implementation Class). If you need more interesting points about Interface then , Click.


But , our point is why all methods are public in interface.Because of  weaker access privileges.Interface means you are going to implement those methods in implementation classes.So, that interface method can accessed by any where , only require to implementing that Interface.When you are declaring a method(Without body) inside interface  , by default you are making that method with the most strong access privileges (public).

  1. Do you really know , what is weaker access privilege ?
  2. Are you really interested on Interface ?
  3. What is Access Specifier when Overriding ?







Hope it will help you.
Any suggestions or comments will appreciated.

No comments:

Post a Comment