Java学习——接口

Java学习——接口

一,定义接口详细说明

1.接口可以多继承,类只能单继承
2.接口中的属性只能为常量,默认由public static final修饰
3.接口中的方法默认由public abstract修饰
4.访问修饰符为public或默认

  • 子类通过implements实现接口中的规范
  • 接口不能创建实例,但可用于声明引用变量类型
  • 一个类实现了接口,必须要实现接口中的所有方法并且只能用public修饰
package com.oop;

public class TestInterface {

    public static void main(String[] args) {
        Volant v=new Angel();
        v.fly();
        Honest h=new GoodMan();
        h.helpOther();
    }
}

interface Volant{
    int FLY_HEIGHT=1000;
    void fly();
    
}

interface Honest{
    void helpOther();
}

class Angel implements Volant,Honest{//实现类可以实现多个父接口

    @Override
    public void helpOther() {
        System.out.println("Angel.helpOther()");
        
    }

    @Override
    public void fly() {
        System.out.println("Angel.fly()");
        
    }
    
}

class GoodMan implements Honest{

    @Override
    public void helpOther() {
        System.out.println("GoodMan.helpOther()");
        
    }
    
}

class Birdman implements Volant{

    @Override
    public void fly() {
        System.out.println("Birdman.fly()");
        
    }
    
}
package com.oop;

public class TestInterface2 {

}

interface A{
    void testa();
}

interface B{
    void testb();+
}

interface C extends A,B{
    void testc();
}

//接口可以多继承,类只有单继承
class Myclass implements C{

    @Override
    public void testa() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void testb() {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void testc() {
        // TODO Auto-generated method stub
        
    }
    
}

说明一个接口在继承别的接口后,实现过程中也要实现父接口中的方法

你可能感兴趣的:(Java学习——接口)