zoukankan      html  css  js  c++  java
  • Java基础学习13--接口

    java的接口使用Interface来定义,接口中只能包含静态常量和抽象方法。

    1.定义接口并使用

    定义如下:

     1 package com.example.inte;
     2 
     3 public interface MyInterface {
     4     public static final String NAME = "zhangsan";
     5     int AGE = 14;// 默认公开静态常量
     6 
     7     public abstract void say();
     8 
     9     // 默认公开抽象方法
    10     //jdk1.8 接口默认实现
    11     default void eat() {
    12         System.out.println("默认eat");
    13     }
    14 }

    注:jdk1.8中,接口的抽象方法可以有默认的实现。

    定义实现类:

    1 package com.example.inte;
    2 
    3 public class Impl implements MyInterface {
    4     @Override
    5     public void say() {
    6         // TODO Auto-generated method stub
    7         System.out.println("我是:" + this.NAME + ",我今年" + this.AGE + "岁");        
    8     }
    9 }

    测试:

    1 package com.example.inte;
    2 
    3 public class TestInte {
    4     public static void main(String[] args) {
    5         MyInterface interface1 = new Impl();
    6         interface1.eat();//调用默认方法
    7         interface1.say();//调用实现类的方法
    8     }    
    9 }

    执行结果为:

    默认eat
    我是:zhangsan,我今年14岁

    2.接口与抽象类

    相同点:

    (1)可编译成字节码文件。

    (2)不能创建对象。

    (3)可以作为引用类型。

    (4)具备Object类型中的方法。

    不同点:

    接口中没有构造方法、动态代码块、静态代码块。

    接口的定义:代表了某种能力。

    方法的定义:能力的具体要求。

  • 相关阅读:
    [Luogu] 封锁阳光大学
    [other] Div
    [USACO11DEC] 牧草种植Grass Planting
    [Luogu] 仓鼠找sugar
    [USACO15DEC]最大流Max Flow
    [noip-2013] 货车运输
    [模板] 普通平衡树
    [Luogu] 树链剖分
    [ZJOI2008] 树的统计Count
    大组合数取模
  • 原文地址:https://www.cnblogs.com/asenyang/p/14386554.html
Copyright © 2011-2022 走看看