接口回调
接口是为了实现多态。这里“接口 对象 = new 实现类”,这样新构造出来的东西本质上是个接口(也就是父类)。我觉得它有点类似于List和ArrayList之间的关系,ArrayList是接口List的一个实现类,(List接口还有很多别的实现类e.g. LinkedList)。按理说其实可以直接声明ArrayList a = new ArrayList()。但是这样的话一旦你需要的不是arraylist(比方说你想改成linkedlist的话),就需要把a调用的所有ArrayList独有而List没有的方法全都改掉,这样的话很消耗工作量。
但是如果写的是List a = new ArrayList()的话,只需要将ArrayList改成LinkedList即可,且之后的代码不需要改,因为a调用的方法都是大家共有的(只不过大家对这个方法的诠释(接口中抽象方法的实现)不一样而已,只是函数方法名字都一样)。
不过以上都得看具体需求,假如我需要建立的对象就是必须要调用某个特定实现类的特定方法(e.g.我就是需要ArrayList()中独有的成员方法),那么ArrayList a = new ArrayList()完全没问题。
p.s.
如果是 List a = new ArrayList(),那么a只能调用list中有的,但是不能调ArrayList中独有的。
Q:如果是ArrayList a = new ArrayList(),那么a可以调用ArrayList中所有的。
那既然这样,是不是List a = new ArrayList() 等同于List a = new LinkedList()?毕竟a调用的都是大家都有的方法?
A:并不是 都有的方法是方法名一样,方法体中具体的实现是可以不一样的。(多态)
第一个例子:
package exp_3;
public interface InterfaceA6 {
int method(int n);
}
package exp_3;
class ClassA implements InterfaceA6{
public int method(int n) {
int sum=0;
for(int i=1; i<=n; i++) {
sum += i;
}
System.out.println(sum);
return sum;
}
}
class ClassB implements InterfaceA6{
public int method(int n) {
int res =1;
for(int i=1; i<=n; i++) {
res *=i;
}
System.out.println(res);
return res;
}
}
public class E6{
public static void main(String[] args) {
// TODO Auto-generated method stub
InterfaceA6 a = new ClassA();
a.method(5);
InterfaceA6 b = new ClassB();
b.method(4);
}
}第二个例子:
package exp_3;
public interface Compute {
int computer(int n, int m);
}
package exp_3;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class TestCompute {
public static void main(String[] args) {
// TODO Auto-generated method stub
UseCompute u = new UseCompute();
u.useCom(new sum(), 2,1);
u.useCom(new minus(), 2,1);
u.useCom(new multiple(), 2,1);
u.useCom(new divide(), 2,1);
// List a =new ArrayList();
}
}
class UseCompute{
public void useCom(Compute com, int one, int two) {
System.out.println(com.computer(one, two));
}
}
class sum implements Compute{
public int computer(int n, int m) {
return n+m;
}
}
class minus implements Compute{
public int computer(int n, int m) {
return n-m;
}
}
class multiple implements Compute{
public int computer(int n, int m) {
return n*m;
}
}
class divide implements Compute{
public int computer(int n, int m) {
return n/m;
}
}