关于JAVA接口

注:写这篇博客主要是为了强化一下记忆。(本文主要摘自 阎宏老师的《java与模式》,代码是自己根据理解所写)
1:什么是接口:
一个java接口是一些方法特征的集合,这些方法特征当然是来自于具体方法,但是它们一般来自于一些在系统中不断出现的方法。接口只有方法的特征,没有方法的实现,因此这些方法在不同的地方被实现时,可以具有完全不同的行为。(摘自 《java与模式》)
2:接口是对可插入行的保证
在一个类等级结构中的任何一个类可以实现一个接口,这个接口会影响到此类的所有子类,但是不会影响到此类的任何超类,此类不得不实现这个接口所规定的方法,而其子类则可以自动继承到这些方法,当然也可以选择置换(重写)所有的这些或者一部分方法。

package com.test;

/**
 * 父类接口
 * Created by OldZhu on 2017/8/9.
 */
public interface FatherInterfaceTest {
    public void sayHello();
    public final String name ="With your hand, with your feet, with your eyes, with your brain, what you touch, what you see, what you imagine, this is your world.";

}
package com.test;

/**
 * Created by OldZhu on 2017/8/9.
 */
public interface InterfaceTest extends  FatherInterfaceTest{
    public  String helloPeople(String peoplename);
}
package com.test;

/**
 * Created by OldZhu on 2017/8/9.
 */
public class HelloInterface implements  InterfaceTest {
    @Override
    public String helloPeople(String peoplename) {

        return "hello,"+peoplename;
    }

    @Override
    public void sayHello() {
        System.out.println("say hello");
    }
}
package com.test;

/**
 * Created by OldZhu on 2017/8/9.
 */
public class SonOfHelloInterface extends HelloInterface {

    public static void main(String[] args) {
      InterfaceTest hello = new SonOfHelloInterface();
        System.out.println(hello.helloPeople("zys"));
        hello.sayHello();
        System.out.println(hello.name);
        System.out.println(name);
    }
}
//控制台输出
hello,zys
say hello
With your hand, with your feet, with your eyes, with your brain, what you touch, what you see, what you imagine, this is your world.
With your hand, with your feet, with your eyes, with your brain, what you touch, what you see, what you imagine, this is your world.

3:类等级结构
java接口以及java抽象类一般用来作为一个类型等级机构的起点。
这里写图片描述
混合类型
如果一个类已经有了一个主要的超类型(可以通过继承或者实现),那么通过再次实现一个接口,这个类可以拥有一个次要的超类型,这种次要的超类型就叫做混合类型(Mixin Type)。
如:TreeMap类具有多个类型,主要是AbstractMap,Serializable是一个次要类型,表明这个实例是可以串行化的。

常见用法:
1:单方法接口(如:Runnable)
2:标识接口
无任何方法和属性的接口(如:java.io.Serializable,java.rmi.Remote)
3:常量接口
接口中的常量在具体类的使用中不需要加上接口类名就可以直接使用,这种做法被称为代码模式,被认为是错误的使用方法,不提倡使用。如上面的FatherInterfaceTest 接口中的name。
4:多方法接口

猜你喜欢

转载自blog.csdn.net/zys351148/article/details/76961551