Question

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?

Was it helpful?

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.

OTHER TIPS

Program to an interface

The only advantage is that you are hiding the exact implementation by using interface MyInterface and you are free to change the implementation in future.

But when you use concrete class then you are bound to the behavior of that class.

Suppose you were passing List<Integer> in method of other class then it can be any implementation of list the user does not care. But if you pass ArrayList<Integer> then the user can use ArrayList specific methods and you will not be able to change it to LinkedList in future.

So case2() is better than case1()

There is no other benefit.

Do they have any advantages in terms of performance , visibility , protecting the object from illegal usage?

Performance will be same when passing any kind of reference, it does not matter whether it is an interface or concrete class reference.

EDIT: As per the comment and further post of @maaartinus there seems to be some difference in performance when using interfaces. But again I would not be worried unless it proven to be a bottleneck in my code, which is going to be never.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top