Java中传递接口引用和类引用之间的区别

Dav*_*can 3 java performance encapsulation interface object

如示例所示,传递接口引用或类引用之间有什么区别;

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);
Run Code Online (Sandbox Code Playgroud)

case1和case2之间的主要区别是什么?它们在性能,可见性,保护对象免受非法使用方面是否具有任何优势?像这样使用它有什么缺点吗?

sti*_*ike 5

通过传递接口,您将创造机会传递实现该接口的所有类。但是在case1中,您只能传递MyClass和及其子类。

例如考虑以下情况

public class YourClass implements MyInterface
{

 public void foo()
    {
        doJob();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在case2中,您可以传递MyClass和YourClass的实例。但万一,你不能。

现在,它的重要性是什么?

在OOP中,建议编程为接口而不是类。因此,如果您考虑好的设计,就不会有case1。只有case2会为您完成这项工作。