interface(接口)
java只支持单继承
接口帮助我们实现多继承——一个类可以实现多个接口
接口是一种特殊的抽象类
抽象类中所有方法都是抽象方法,所有成员变量都是静态成员变量
但是这个抽象类不用写abstract,抽象方法也不用写abstract ,因为interface中只能定义抽象方法
interface中声明的属性默认为 public static final,也只能是这个
interface中只能定义抽象方法,默认且只能为public
public interface Runner{
public static final int id = 1;//int id = 1;
public void start();
public void run();
public void stop();
}
example
interface Singer{
public void sing();
public void sleep();
}
class Student implements Singer{//这里不是extends,而是implements,但是可以看做继承
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 studying");
}
public void sleep(){
System.out.println("Stdent is sleeping");
}
}
interface Painter{
public void paint();
public void eat();
}
class Teacher implements Singer, Painter{//这里不是extends,而是implements,但是可以看做继承
private String name;
Teacher(String name){
this.name = name;
}
public void teach(){
System.out.println("teaching");
}
public String getName(){
return name;
}
public void sing() {//方法重写
System.out.println("Teacher is studying");
}
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 args[]){
Singer s1 = new Student("le");//new出来的Student中包含 name, study(), sing(), sleep(),但是,就像对象转型中,父类引用指向子类对象,实际上指向父类
s1.sing();
s1.sleep();
//s1.study();
Singer s2 = new Teacher("LE");
s2.sing();
s2.sleep();
//s2.paint();
//s2.eat();
/s2.teach();
Painter p1 = (Painter) s2;
p1.paint();
p1.eat();
}
}
example
abstract class Animal{
private String name;
abstract void enjoy();
}
interface Protectable{
public void beProtectable();
}
interface Valueable{
public double getMoney();
}
interface A extends Protectable{//接口之间可以相互继承
void m();
}
class GoldMoney extends Animal implements Protectable, Valueable{
public void beProtectable(){
System.out.println("live in the room");
}
public double getMoney(){
return 10000;
}
public void enjoy(){
System.out.println("~~叫");
}
}