传递接口引用或类引用之间有什么区别,如示例所示;
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 之间的主要区别是什么?它们在性能、可见性、保护对象免遭非法使用方面有什么优势吗?这样使用有什么缺点吗?
通过传递接口,您将有机会传递所有实现该接口的类。但在case1中你只能通过MyClass
及其子类。
例如考虑以下情况
public class YourClass implements MyInterface
{
public void foo()
{
doJob();
}
}
现在,在 case2 中,您可以传递 MyClass 和 YourClass 的实例。但在 case1 中你不能。
现在,它的重要性是什么?
在 OOP 中,建议对接口而不是类进行编程。所以如果你考虑好的设计就不会有case1。只有 case2 可以为您完成这项工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)