接口
程序员文章站
2022-06-13 19:12:53
...
接口
1.多个无关的类可以实现同一个接口;
2.一个类可以实现多个无关的接口;
3.与继承关系类似,接口与现实类之间存在多态性;
4.定义Java类的语法格式:
class[extends]
[implements[,]*]{}
5.接口(interface)时抽象方法和常量值的定义的集合;
6.从本质上讲,接口时一种特殊的抽象类,这种类中只包含常量和方法的定义,而没有变量和方法的实现;
7.接口定义举例:
public interface Runner{
public static final int id = 1;
//定义为public static final是为了修正多继承的时候容易出现问题的地方。
public void start();
public void run();
public void stop();
}
接口特性
1.接口可以多重实现;
2.接口中声明的属性默认为 public static final 的;也只能是 public static final 的;
3.接口中只能定义抽象方法,而且这些方法默认为 public 的、也这能是 public 的;
4.接口可以继承其它的接口,并添加新的属性和抽象方法。
例1:
interface Singer{
public void sing();
public void sleep();
}
//继承
class Student implements Singer{
private String name;
Student(String name){
this.name = name;
}
public void study(){
System.out.println("studying");
}
public String getName(){
return name;
}
//重写
public void sing(){
System.out.println("student is singing");
}
public void sleep(){
System.out.println("student is sleeping");
}
}
例2
//接口一
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 void study(){
System.out.println("studying");
}
public String getName(){
return name;
}
//重写
public void sing(){
System.out.println("student is singsing");
}
public void sleep(){
System.out.println("student is sleeping");
}
}
//继承
class Teacher implements Singer,Painter{
private String name;
public String getString(){
return name;
}
Teacher(String name){
this.name = 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 Test{
//主方法
public static void main(String[] agrs){
Singer s1 = new Student("le");
s1.sing();
s1.sleep();
Singer s2 = new Teacher("steven");
s2.sing();
s2.sleep();
Painter p1 = (Painter)s2;
p1.paint();
p1.eat();
}
}