java中的接口interface
接口(interface)是抽象方法和常量值的定义的集合。
从本质上讲,接口是一种特殊的抽象类,这种抽象类值包含方法和常量的定义,没有变量和方法的实现。
TestInterface.java
//唱歌的接口 interface Singer { //唱歌 public void sing(); //睡觉 public void sleep(); } //画画的接口 interface Painter { //画画 public void paint(); //吃饭 public void eat(); } //学生类实现Singer接口 class Student implements Singer { //成员变量 private String name; //构造方法 Student(String name) { this.name = name; } //get set方法 public String getName() { return name; } public void setName(String name) { this.name = name; } //自定义方法——学 public void study() { System.out.println("studying..."); } //重写,实现Singer接口里面的方法 //唱歌 public void sing() { System.out.println("student is singing..."); } //睡觉 public void sleep() { System.out.println("student is sleeping..."); } } //教师类实现Singer,Painter接口 class Teacher implements Singer, Painter { //成员变量 private String name; //构造方法 Teacher(String name) { this.name = name; } //get set方法 public String getName() { return name; } public void setName(String name) { this.name = name; } //自定义方法——教 public void teache() { System.out.println("teaching..."); } //重写,实现Singer接口里面的方法 //唱歌 public void sing() { System.out.println("teacher is singing..."); } //睡觉 public void sleep() { System.out.println("teacher is sleeping..."); } //重写,实现Painter接口里面的方法 //画画 public void paint() { System.out.println("teacher is painting..."); } //吃饭 public void eat(){ System.out.println("teacher is eating..."); } } public class TestInterface { public static void main(String[] args) { //声明Singer接口引用指向Student Singer s1 = new Student("le"); s1.sing(); s1.sleep(); //声明Singer接口引用指向Teacher Singer s2 = new Teacher("steven"); s2.sing(); s2.sleep(); //将Singer转化为Painter Painter p = (Painter)s2; p.paint(); p.eat(); //测试Student和Teacher的自定义方法 Student s = (Student)s1; s.study(); Teacher t = (Teacher)s2; t.teache(); } }
结果:
F:\java>javac TestInterface.java F:\java>java TestInterface student is singing... student is sleeping... teacher is singing... teacher is sleeping... teacher is painting... teacher is eating... studying... teaching... F:\java>
补充:
Valuable.java
//interface接口 public interface Valuable { public double getMoney(); } //interface接口 interface Protectable { public void beProtected(); } //interface接口继承接口 interface A extends Protectable { void m(); void getMoney(); } //abstract抽象类 abstract class Animal { private String name; abstract void enjoy(); } //class类继承abstract,实现interface class GoldenMonkey extends Animal implements Valuable, Protectable { public double getMoney() { return 10000; } public void beProtected() { System.out.println("live in the room"); } public void enjoy() { } public void test() { Valuable v = new GoldenMonkey(); v.getMoney(); Protectable p = (Protectable)v; p.beProtected(); } } //class实现interface class Hen implements A { public void m() {} public void beProtected() {} public double getMoney() { return 1.0; } public void getMoney() {} }