interface 接口

接口(interface)是抽象方法和常量值的定义的集合

从本质上讲,接口是一种特殊的抽象类,这种抽象类中只包含常量和方法的定义,而没有变量和方法的实现

接口定义举例:

public interface Runner {

   public static final int id = 1;

 

   public void start();

   public void run();

   public void stop();

}

 

 

 

接口:

1,多个无关的类可以实现同一个接口

2,一个类可以实现多个无关的接口

3,与继承关系类似,接口与实现类之间存在多态性

 

接口特性:

1,接口可以多重实现

2,接口中声明的属性默认为public static final ;也只能是public static final ;

3,接口中只能定义抽象方法,而且这些方法默认为public的,也只能是public的;

4,接口可以继承其他的接口,并添加新的属性和抽象方法

 

例:

interface Singer {
 public void sing();
 public void sleep();
}

 

interface Painter {
 public void paint();
 public void eat();
}

 

class Student implements Singer {
 private String name;
 Student(String name) {this.name = name;}
 public String getName() {return name;}
 public void study() {System.out.println("studying");}
 public void sing() {System.out.println("student is singing");}
 public void sleep() {System.out.println("student is sleeping");}
}

 

class Teacher implements Singer,Painter {
 private String name;
 Teacher(String name) {this.name = name;}
 public String getName() {return name;}
 public void teach() {System.out.println("teaching!");}
 public void sing() {System.out.println("teacher is singing");}
 public void sleep() {System.out.println("teacher is sleeping");}
 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 s1 = new Student("l1");
  s1.sing();
  s1.sleep();
  Singer s2 = new Teacher("job");
  s2.sing();
  s2.sleep();
  Painter p1 = (Painter)s2;
  p1.paint();
  p1.eat();
 }

}

 

运行结果:

student is singing
student is sleeping
teacher is singing
teacher is sleeping
teacher is painting
teacher is eating

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值