Java Interface
发布日期:2021-06-29 18:38:14 浏览次数:2 分类:技术文章

本文共 7841 字,大约阅读时间需要 26 分钟。

文章目录

Java Interface

  • 是抽象类型,抽象方法的集合
  • 类通过implements、来implements接口的抽象方法。
  • 接口不是类,编写接口的方式和类很相似
    • 类描述对象的属性和方法。
    • 接口则包含类要实现的方法。
  • 接口无法被实例,但可被实现。
  • Java 中,接口类型可用来声明一个变量,他们可以成为一个空指针,或是被绑定在一个以此接口实现的对象。

在这里插入图片描述

接口与类相似点:

  • 接口文件保存在.java文件,文件名用接口名。
  • 接口的字节码文件保存在.class 结尾的文件中。
  • 接口相应的字节码文件必须在与包名称相匹配的目录结构中。

接口与类的区别:

  • 不能用于实例化
  • 无构造方法。
  • 方法必须是抽象方法。
  • 不含成员变量,除static和 final 变量。
  • 接口不是被类继承了,而是要被类实现。
    • 支持多继承。

接口特性

  • 方法会被隐式的指定public abstract(其他修饰符报错)。
  • 接口中可含有变量,但是接口中的变量会被隐式的指定为 public static final 变量(并且只能是 public,用 private 修饰会报编译错误)。
  • 方法是不能在接口中实现,只能由实现接口的类来实现接口中的方法。

抽象类和接口区别

  • 抽象类中的方法可以有方法体,就是能实现方法的具体功能,

    • 接口中的方法不行。
  • 抽象类中的成员变量可以是各种类型的,

    • 接口中只能是 public static final 类型的。
  • 接口中不能含有静态代码块以及静态方法(用 static 修饰的方法),

    • 抽象类可以有静态代码块和静态方法。
  • 一个类只能继承一个抽象类,而一个类却可以实现多个接口。

  • JDK 1.8 后,接口里可以有静态方法和方法体了。

接口的声明

[可见度] interface 接口名称 [extends 其他的接口名] {
// 声明变量 // 抽象方法}
/* NameOfInterface.java */import java.lang.*;//引入包 public interface NameOfInterface{
//任何类型 final, static 字段 //抽象方法}
  • 接口是隐式抽象的,当声明一个接口时,不必用abstract
  • 每个方法是隐式抽象的,声明时不要abstract
  • 接口中的方法都是公有的。

例子

/* Animal.java */interface Animal {
public void eat(); public void travel();}

接口的实现

  • 类实现接口时,类要实现接口中所有方法。
    • 否则,类必须声明为抽象的
...implements 接口名称[, 其他接口名称, 其他接口名称..., ...] ...
/* MammalInt.java */public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats"); } public void travel(){
System.out.println("Mammal travels"); } public int noOfLegs(){
return 0; } public static void main(String args[]){
MammalInt m = new MammalInt(); m.eat(); m.travel(); }}
  • 重写接口中声明的方法时,注意:
    • 类在实现接口方法时,不能抛出强制性异常,
      • 只能在接口中,或者继承接口的抽象类中抛出该强制性异常。
    • 类在重写方法时要保持一致的方法名,且应该保持相同或者相兼容的返回值类型。
    • 如果实现接口的类是抽象类,那么就没必要实现该接口的方法。
  • 注意
    • 一个类可同时实现多个接口。
    • 一个类只能继承一个类,但能实现多个接口。
    • 一个接口能继承另一个接口

接口的继承

  • 接口能继承另一接口,
  • 子接口继承父接口的方法。
// Sports.javapublic interface Sports{
public void setHomeTeam(String name); public void setVisitingTeam(String name);} // Football.javapublic interface Football extends Sports{
public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter);} // Hockey.javapublic interface Hockey extends Sports{
public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot);}
  • Hockey接口自己声明四个,从Sports继承两个,
  • 实现Hockey接口的类需实现六个。

接口的多继承

  • Java中,类的多继承是不合法,接口允许多继承。
public interface Hockey extends Sports, Event

标记接口

  • 最常用的是不包含任何方法的接口。
  • 它仅表明它的类属于一个特定的类型,供其他代码来测试允许做一些事情。
  • 作用:就是给某个对象打个标(盖个戳),使对象拥有某个或某些特权。

java.awt.event包中的 MouseListener 接口继承的 java.util.EventListener 接口定义:

package java.util;public interface EventListener{
}

标记接口两目的:

  • 建立一个公共的父接口:
  • 如EventListener接口,这是由几十个其他接口扩展的Java API,你可以使用一个标记接口来建立一组接口的父接口。
  • 当一个接口继承了EventListener接口,Java虚拟机(JVM)就知道该接口将要被用于一个事件的代理方案。
  • 向一个类添加数据类型:
    • 是标记接口最初目的,
    • 实现标记接口的类不需要定义任何接口方法(因为标记接口根本就没有方法),但是该类通过多态性变成一个接口类型。

以SQL JDBC的ResultSet接口为例

public interface ResultSet extends Wrapper, AutoCloseable {
boolean next() throws SQLException; void close() throws SQLException; boolean wasNull() throws SQLException; String getString(int columnIndex) throws SQLException; boolean getBoolean(int columnIndex) throws SQLException; byte getByte(int columnIndex) throws SQLException; short getShort(int columnIndex) throws SQLException; int getInt(int columnIndex) throws SQLException; long getLong(int columnIndex) throws SQLException; float getFloat(int columnIndex) throws SQLException; double getDouble(int columnIndex) throws SQLException; @Deprecated BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException; byte[] getBytes(int columnIndex) throws SQLException; java.sql.Date getDate(int columnIndex) throws SQLException; java.sql.Time getTime(int columnIndex) throws SQLException; java.sql.Timestamp getTimestamp(int columnIndex) throws SQLException; java.io.InputStream getAsciiStream(int columnIndex) throws SQLException; @Deprecated java.io.InputStream getUnicodeStream(int columnIndex) throws SQLException; java.io.InputStream getBinaryStream(int columnIndex) throws SQLException; String getString(String columnLabel) throws SQLException; boolean getBoolean(String columnLabel) throws SQLException; byte getByte(String columnLabel) throws SQLException; short getShort(String columnLabel) throws SQLException; int getInt(String columnLabel) throws SQLException; long getLong(String columnLabel) throws SQLException; float getFloat(String columnLabel) throws SQLException; double getDouble(String columnLabel) throws SQLException; @Deprecated BigDecimal getBigDecimal(String columnLabel, int scale) throws SQLException; byte[] getBytes(String columnLabel) throws SQLException; @Deprecated java.io.InputStream getUnicodeStream(String columnLabel) throws SQLException; 删了好多啊!!!!!!!!!!!!!!!!!!!!!!!! default void updateObject(String columnLabel, Object x, SQLType targetSqlType) throws SQLException {
throw new SQLFeatureNotSupportedException("updateObject not implemented"); }}
public interface ISQLServerResultSet extends ResultSet {
int TYPE_SS_DIRECT_FORWARD_ONLY = 2003; int TYPE_SS_SERVER_CURSOR_FORWARD_ONLY = 2004; int TYPE_SS_SCROLL_STATIC = 1004; int TYPE_SS_SCROLL_KEYSET = 1005; int TYPE_SS_SCROLL_DYNAMIC = 1006; int CONCUR_SS_OPTIMISTIC_CC = 1008; int CONCUR_SS_SCROLL_LOCKS = 1009; int CONCUR_SS_OPTIMISTIC_CCVAL = 1010; DateTimeOffset getDateTimeOffset(int var1) throws SQLException; DateTimeOffset getDateTimeOffset(String var1) throws SQLException; void updateDateTimeOffset(int var1, DateTimeOffset var2) throws SQLException; void updateDateTimeOffset(String var1, DateTimeOffset var2) throws SQLException;}
public final class SQLServerResultSet implements ISQLServerResultSet {
private static int lastResultSetID = 0; private final String traceID; static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.SQLServerResultSet"); private static final Logger loggerExternal = Logger.getLogger("com.microsoft.sqlserver.jdbc.ResultSet"); private final String loggingClassName; private final SQLServerStatement stmt; private final int maxRows; private ResultSetMetaData metaData; private boolean isClosed = false; private final int serverCursorId; private int fetchDirection; private int fetchSize; private boolean isOnInsertRow = false; private boolean lastValueWasNull = false; private int lastColumnIndex; private boolean areNullCompressedColumnsInitialized = false; private RowType resultSetCurrentRowType; private Closeable activeStream; private final ScrollWindow scrollWindow; private static final int BEFORE_FIRST_ROW = 0; private static final int AFTER_LAST_ROW = -1; private static final int UNKNOWN_ROW = -2; private int currentRow; private boolean updatedCurrentRow; private boolean deletedCurrentRow; static final int UNKNOWN_ROW_COUNT = -3; private int rowCount; private final Column[] columns; private CekTable cekTable; private TDSReader tdsReader; private final SQLServerResultSet.FetchBuffer fetchBuffer; private SQLServerException rowErrorException; private int numFetchedRows; private static synchronized int nextResultSetID() {
return ++lastResultSetID; } public String toString() {
return this.traceID; } String logCursorState() {
return " currentRow:" + this.currentRow + " numFetchedRows:" + this.numFetchedRows + " rowCount:" + this.rowCount; } String getClassNameLogging() {
return this.loggingClassName; }

@Deprecated

  • 若某类或某方法加上该注解之后,表示此方法或类不再建议使用,调用时也会出现删除线,
  • 但并不代表不能用,只是不推荐使用,因为还有更好的方法可以调用。

转载地址:https://cyj666.blog.csdn.net/article/details/103165587 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:synchronized 关键字+ final关键字
下一篇:如何配置SQL Server ODBC数据源

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月15日 23时05分25秒