Search code examples
javaperformanceobjectinterfaceencapsulation

The difference between passing interface reference and class reference in java


Is there any difference between passing Interface reference or class reference as shown in example ;

Interface MyInterface
{
     void foo();
}
public class MyClass implements MyInterface
{


 public void foo()
    {
        doJob();
    }
}

....
//in another class or etc..
public void case1(MyClass mc)
{
    mc.foo();
}

public void case2(MyInterface mi)
{
    mi.foo();
}
....
//In somewhere
MyClass mc = new MyClass();
case1(mc);
case2(mc);

What are the key differences between case1 and case2? Do they have any advantages in terms of performance , visibility , protecting the object from illegal usage? Are there any disadvantages in using it like this?


Solution

  • By passing the interface you are creating the opportunity to pass all the classes which implements the interface. But in case1 you can only pass the MyClass and its subclasses.

    For example think about the following case

    public class YourClass implements MyInterface
    {
    
     public void foo()
        {
            doJob();
        }
    }
    

    Now in case2 you can pass both the instance of MyClass and YourClass. but in case1 you can't.

    Now, what is the importance of it?

    In OOP it is recommended to program to the interface instead of class. So if you think about good design there will be no case1. Only case2 will do the job for you.