java中传递接口引用和类引用之间的区别 [英] The difference between passing interface reference and class reference in java

查看:236
本文介绍了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);

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

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?

推荐答案

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

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.

例如,考虑以下情况

public class YourClass implements MyInterface
{

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

现在在case2中你可以传递MyClass的两个实例和YourClass。但是在case1中你不能。

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?

在OOP中,建议编程到接口而不是类。因此,如果你考虑好的设计,就没有案例1。只有case2才能为你完成工作。

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.

这篇关于java中传递接口引用和类引用之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆