接口使用之我见

定义一个借口如下:
package org.liufei.Interface.test;

public interface TestInterface {

public String test() ;

}
如下是两个实现接口的类:
类1:
package org.liufei.Interface.test;

public class TestClass implements TestInterface{

public String test() {
// TODO Auto-generated method stub
return "Hello test1!!";

}

}
类2:
package org.liufei.Interface.test;

public class TestClass1 implements TestInterface {

public String test() {
// TODO Auto-generated method stub
return "Hello test2!!";
}
}

定义一个回调类:
package org.liufei.Interface.test;

public class TestSession {

public TestInterface getInterface1() {
TestInterface test = new TestClass();
return test;
}

public TestInterface getInterface2() {
TestInterface test = new TestClass1();
return test;
}

}
测试类如下:
package org.liufei.Interface.test;

public class TestMain {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestSession s = new TestSession() ;
TestInterface test1 = s.getInterface1() ;
System.out.println(test1.test()) ;
TestInterface test2 = s.getInterface2() ;
System.out.println(test2.test()) ;

}

}
控制台打印:
Hello test1!!
Hello test2!!

我平时就是这么用的,不知道对不对,感觉还好,盼高手指教!!!

你可能感兴趣的:(接口)