Java 只支持单继承,那么要封装更多的东西,多继承怎么办?用接口
接口可以多重实现:一个类可以有多个接口,实现多继承
接口中声明的属性默认为 public static final
接口里的方法只能用抽象方法,只能是public的
类实现(继承)接口里的方法用implements,而不是extends
//package TestInterface;
//接口interface;特殊的抽象类
public interface TestInterface {//class 写成interface
public static final int id=1;//和这个int id=1是一样的;接口中声明的属性默认为 public static final,可省略
}
interface Singer{
public void sing();//抽象类 只定义标准,不写具体方法
public void sleep();
}
interface Painter{
public void paint();
public void eat();
}
class Student implements Singer{//类实现(继承)接口里的方法用implements,而不是extends
private String name;
Student(String name){
this.name=name;}
public String getName(){
return name;
}
public void study(){
System.out.println("student is 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 sing(){
System.out.println("student is singing");
}
public void sleep(){
System.out.println("student is sleeping");
}
public void paint(){
System.out.println("student is painting");
}
public void eat(){
System.out.println("student is eating");
}
}