Abstract&Interface

抽象类

  1. 不能new这个抽象类,只能靠继承他的子类去实现它 约束

  2. 抽象类中可以写普通的方法

  3. 抽象方法必须在抽象类中

  4. 抽象方法:只有方法名,没有方法的实现

接口

  1. interface 定义关键字

  2. 接口中的所有定义都是抽象的

    • JDK8版本开始,允许在接口体中定义static方法,允许使用default方法,但不可以定义default的static方法

    • JDK9版本开始,允许在接口体中定义private方法(通常搭配default方法使用)

      interface Com{
         public final int MAX = 100;
         public abstract void add();
         public abstract float sum(float x,float y);
         public default void max(int a,int b){
            System.out.println(Max(a,b));
        }//default方法,可以省略public
         private int Max(int a,int b){
              return a>b?a:b;
        }
      }
  3. implements 实现了接口中的类,要实现接口中的方法

  4. 利用接口实现多继承

    • public interface UserService{
        void add();
      }
      public interface TimeService {
        void timer();
      }
      public class UserServiceImpl implements UserService,TimeService{
        void add(){}
          void timer(){}
      }     
posted @ 2022-03-25 20:13  CC&  阅读(29)  评论(0)    收藏  举报