如果一个类中的所有方法都是抽象方法,则这个类称之为接口,并且需要使用interface关键字来声明
代码如下;
interface Animal{
int ID=1;
void shout();
void run();
void breathe();
}
在上面的代码中,Animal就是一个接口,里边的三个方法均为抽象方法,但是我们可以看到,这三个抽象方法均没有被abstract关键字修饰,这是因为在接口中,方法会自动被public abstract 关键字修饰。而且接口在中的变量ID其实也是被public abstract final关键字修饰,相当于一个常量1,也可以用来表明一个全局常量。
但是接口中的方法并没有办法通过实例化对象的方法来解决,这时候就需要创建一个新的子类并且通过使用implements关键字实现接口中所有的方法。
代码如下:
interface Animal{
int ID=1;
void run();
void breathe();
}
class Dog implements Animal{
public void run(){
System.out.println("狗在跑。。。。");
}
public void breathe(){
System.out.println("旺旺。。。。");
}
}
public class Main {
public static void main(String[] args) {
Dog dog1=new Dog();
dog1.breathe();
dog1.run();
System.out.println("ID="+Animal.ID);
}
}
上边是演示的类与接口之间的实现关系,在程序中实际上还可以定义一个接口去继承另一个接口
interface Animal{
int ID=1;
void run();
void breathe();
}
interface LandAnimal extends Animal{
void liveOnland();
}
class Dog implements Animal{
public void run(){
System.out.println("狗在跑。。。。");
}
public void breathe(){
System.out.println("旺旺。。。。");
}
public void liveOnland(){
System.out.println("动物生活在陆地上。。。。");
}
}
public class Main {
public static void main(String[] args) {
Dog dog1=new Dog();
dog1.breathe();
dog1.run();
dog1.liveOnland();
System.out.println("ID="+Animal.ID);
}
}