兵马未动粮草先行,下面我们看一下接口是怎么样去定义的?
定义接口:
interface A{
public static final String MSG="YOOTK";
public abstract void print();
}
通过上面的例子,可以看出接口的使用原则为以下几个原则;
1、接口必须要有子类,但是此时一个子类可以使用implement关键字实现多个接口,避免单继承局限。
2、接口的子类(如果不是抽象类),必须要覆写接口中的全部抽象方法。
3、接口的对象可以利用子类对象的向上转型进行实例化操作。
实现接口:
interface A{
public static final String MSG="Zsd";
public abstract void print();
}
interface B{
public abstract void get();
}
class X implements A,B{
public void print(){
System.out.println("A接口的抽象方法!");
}
public void get(){
System.out.println("B接口的抽象方法");
}
}
public class TestDemo{
public static void mian(String args[]){
X x = new X();
A a = x;
B b = x;
a.print();
b.get();
System.out.println(A.MSG);
}
}
在实际的开发过程中,存在需要继承其他的类,之后有部分功能需要继承接口的使用
采用以下原则:
应该采用先继承(extends) 后实现接口(implements)的顺序完成。
以下为基本使用的例子:
interface A{
public abstract void print();
}
interface B{
public abstract void get();
}
abstract class C{
public static void change();
}
class X extends X implements A,B{
public void print(){
System.out.println("A的抽象方法");
}
public void get(){
System.out.println("B的抽象方法");
}
public void change(){
System.out.println("C的抽象方法");
}
}
一个抽象类可以继承一个抽象类或者实现若干个接口,但是一个接口却不能继承抽象类,一个接口可以使用extends关键字同时继承多父接口。
interface A{
public void funA();
}
interface B{
public void funB();
}
interface C extends A,B{
public void funC();
}
class X implements C{
public void funA(){
System.out.println("A的抽象方法");
}
public void funB(){
System.out.println("B的抽象方法");
}
public void funC(){
System.out.println("C的抽象方法");
}
}
接口的应用例子—工厂设计模式:
interface Fruit{
public void eat();
}
class Apple implements Fruit{
public void eat(){
System.out.println("吃苹果");
}
}
public class TestDemo{
public static void main(String args[]){
Fruit f = new Apple();
f.eat();
}
}
在实际的代码模块设计过程中,需要注意以下两点:
1、客户端调用简单
2、程序代码的修改,不影响客户端的调用,即使用者可不去关心代码是否变更。
接口应用模式—代理设计模式:
代理设计就是指一个代理主体来操作真实主题,真实主题执行具体的业务操作,而代理主题负责其他相关业务的处理
interface Network{
public void browse();
}
class Real implements Network{
public void browse(){
System.out.println("这是真实上网服务器!");
}
}
class Proxy implements Network{
private Network network();
public Proxy(Network network){
this.network = network;
}
public void check(){
System.out.printn("检查用户的上网安全性");
}
public void browse(){
this.check();
this.network.browse();
}
}
public class TestDemo{
public static void main(String args[]){
Network net = NULL;
net = new Proxy(new Real());
net.browse();
}
}