-
2016-10-30 19:08:24
interface接口抽象类中包含要实现的子类的通用功能。子类的创建则通过implement方法继承接口,实现具体子功能;
接口类是抽象类,不能直接在安卓的activity中调用,此时必须新建一个连接activity与接口的新类a,在此类中,利用接口抽象类(interface类)声明一个成员变量,利用调用成员变量的子方法(interface.way())的方式调度接口类中的属性;在a类中还要实现将接口类替换为要实现的子类x的方法f()—this.接口类对象=x;而该子类x是从activity中传递过来的,即在activity中调用a类中的方法,a.f(new 子类());
同样在activity中,也是利用声明一个新建类a的方式对a中的方法进行调度。更多相关内容 -
java中接口(interface)及使用方法示例
2020-08-28 16:28:56主要介绍了java中接口(interface)及使用方法示例,涉及接口定义的简单介绍以及Java语言代码示例,具有一定借鉴价值,需要的朋友可以参考下。 -
java类实现interface以后如何调用
2021-02-12 18:19:18//TestInterface.javapublic interface Singer{public void sing();public void dance();}public interface Women{public void cook();public void care();}class Student implements Singer ...如题,以下代码运行报错,应该这么运行起来呢?
//TestInterface.java
public interface Singer{
public void sing();
public void dance();
}
public interface Women{
public void cook();
public void care();
}
class Student implements Singer {
private String name;
Student(String _name) {
this.name = _name;
}
public void sing() {
System.out.println(this.name + " is singing!");
}
public void dance() {
System.out.println(this.name + " is dancing!");
}
}
class Teacher implements Women, Singer {
private String name;
Teacher(String _name) {
this.name = _name;
}
public void sing() {
System.out.println(this.name + " is singing!");
}
public void dance() {
System.out.println(this.name + " is dancing!");
}
public void cook() {
System.out.println(this.name + " is cooking!");
}
public void care() {
System.out.println(this.name + " is caring!");
}
}
public class TestInterface {
public static void main(String args[]) {
Student s = new Student("li");
s.sing();
s.dance();
Teacher t = new Teacher("wang");
t.sing();
t.dance();
t.cook();
t.care();
}
}
运行结果(java 13,不用javac编译)
-
JAVA中interface接口的使用
2022-04-02 16:35:21文章目录前言一、interface是什么?二、关于interface的使用1.接口的格式代码例子12.用登录方法具体实现代码例子2:抽象类和接口之间的区别总结 前言 随着面向对象思想的发展,类的使用越来越方便,但是有时候类却...提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
随着面向对象思想的发展,类的使用越来越方便,但是有时候类却不能实现对于方法的抽象,只能对于自己的属性的抽象。(所谓抽象简单理解为没有具体的实现)于是我们便在java语言中引出了一种接口的方式(interface)。(以下内容基于JAVA语言)
提示:以下是本篇文章正文内容,下面案例可供参考
一、interface是什么?
interface是一种接口的方式和抽象类很相似,并且接口可以实现多接口,但是在JAVA语言中类的继承不能多继承。interface是一种基于方法进行分类的,其主要目的是为了弥补类相对于方法的抽象。
用一个生动的例子来表示就是:
对于不同的动物都有吃的动作,但是一般的植物就没有吃的动作,有一些特殊的植物也有吃的动作。但是对于植物就不能把吃的动作写上去了,只有在写食人花之类的时候,把吃的动作补充就去也就是implements.这里当然也就需要我们的interface能完成了。二、关于interface的使用
关于接口的使用我们这里使用一个登录的例子进行操作,关于不同的登录,实现登录不同,(比如手机短信登录,密码登录,以及扫码登录等等)所以我们在实现登录操作的时候就有了很多种方法。关于不同的方法的实现就可以implement一个interface
1.接口的格式
定义接口:
【public】interface 接口名【extends 父接口名】{}
实现接口:
【修饰符】class 类名 implements 接口名{}代码例子1
//刚刚新建一个包,查阅资料发现包的创建不能出现关键词,下划线,空格 interface login_interface { public void login(userlogin user,String code);//接口只能定义方法不能实现 } //以下的三个类都是对于这个抽象类的实现 class PwdLogin implements login_interface{ @Override public void login(userlogin user, String code) { //在接口的继承里面必须要把全部的方法都实现了 System.out.println("pwd login"); if(user.pwd.equals(code)){ System.out.println("登录成功!!"); }else System.out.println("密码错误"); } } class PhoneMsglogin implements login_interface{ @Override public void login(userlogin user, String code) { System.out.println("phone login"); if(user.pwd.equals(code)) System.out.println("登录成功!!"); else System.out.println("密码错误!"); } } class codelogin implements login_interface{ @Override public void login(userlogin user, String code) { System.out.println("code login"); if(user.pwd.equals(code)) { System.out.println("登录成功!!"); } else System.out.println("密码错误!"); } }
2.用登录方法具体实现
在上面我们创建了三个具体的类去实现这个接口,但是没有体现出他们的具体作用,这里我们创建出一个用户分别使用不同的方法进行登录随后就会有不同的操作进行,可以直接体现interface的作用
代码例子2:
public class userlogin { // 属性 String name; int age; String pwd; /** // 登录方法(如果只有一种登录方法可以直接不用继承该接口的方法就行) public void login(String pwd){ if(pwd.equals (this.pwd)){ System.out.println("登录成功"); }else { System.out.println("登录失败"); } } **/ // 接口声明的 属性对象名 不能直接实例化 login_interface loginService;//这不是实例化,就像是一个指针指向这个类的对象 public void loginServiceLogin(String code){ loginService.login(this,code); } class Manage{ public static void main(String[] args){ userlogin user = new userlogin(); user.name = "张三"; user.age = 18; user.pwd = "123456"; // 配置 登录方式 PhoneMsgLogin phlogin=new PhoneMsgLogin(); codelogin clogin=new codelogin(); PwdLogin pwdLogin = new PwdLogin(); user.loginService=pwdLogin; // CodeLogin codeLogin = new CodeLogin(); // user.loginService=codeLogin; user.loginServiceLogin ("123456"); user.loginService=clogin; user.loginServiceLogin("123456"); user.loginService=phlogin; user.loginServiceLogin("123456");//直接调用一种方法实现三种不用的方法的使用,这个是实现了程序的多态性 } }
抽象类和接口之间的区别
实际点来说,一个抽象类不能实例化,因为“没有包含足够多的信息来描述一个具体的对象”。但终归属于类,所以仍然拥有普通类一样的定义。依然可以在类的实体(直白点就是能在{}里面)定义成员变量,成员方法,构造方法等。
而对于接口来说接口一般指的就是抽象方法和常量的集合(里面的数据以及方法只能是static和final类型)
总结
以上就是今天要讲的内容,关于interface的用法,我们在使用interface的时候需要的就是理解这个接口是为了实现什么样的方法,比如在java原有的包里面有一个ActionLitener接口,可以实现对于一个按钮的监听(监听器)。这个接口里面只有一个抽象方法就是actionPerformed就是用来实现这个功能的。
-
Golang interface 接口详解
2021-04-14 22:03:44之前写过,golang 是通过 结构体(struct)-方法(method)-接口(interface) 的组合使用来实现面向对象的思想。在之前的文章 Golang 复合类型 和 Golang method 方法详解 已经详细介绍过 struct 和 method,本文将介绍 ...前言
在之前的文章中我们说过,golang 是通过
结构体(struct)-方法(method)-接口(interface)
的组合使用来实现面向对象的思想。在前文 Golang 复合类型 和 Golang method 方法详解 已经详细介绍过struct
和method
,本文将介绍 golang 面向对象的另一个重要组成部分:接口(interface)
。
接口
接口概念
接口是一种抽象的类型,描述了一系列方法的集合,作用是对一系列具有联系的方法做出抽象和概括。接口只定义方法名和参数,而不包含具体的实现,这种抽象的方式可以让程序变得更加灵活更加通用。
在很多语言中,接口都是
侵入式
的,侵入式接口的意思是实现类需要明确声明自己实现了某个接口,这就带来了一个很矛盾的问题,比如 A 调用了 B 的接口,那么 A 一定会希望接口被设计成自己想要使用的样子,但是 B 才是接口的实现方,基于模块设计的单向依赖原则,B 在实现自身的业务时,不应该关心某个具体使用方的要求,一个接口被定义的时候,并不知道自己的方法会被谁实现,也不知道会被怎么样实现。因此,侵入式接口一直是面向对象编程中一个经常遭受质疑的特性。不同的是,golang 的接口是一种
非侵入式
的接口,一个类型不需要明确声明,只要实现了接口的所有方法,这个类型就实现了该接口,这个类型的对象就是这个接口类型的实例。 因此,在 golang 中,不再需要定义类的继承关系,而且在定义接口时候,只需要关心自己需要提供哪些方法,其他的方法有使用方按需定义即可。接口定义
/* 定义接口 */ type interface_name interface { method_name1(input_paras...) [return_type] method_name2(input_paras...) [return_type] method_name3(input_paras...) [return_type] } /* 定义结构体 */ type struct_name struct { /* variables */ } /* 实现接口方法 */ func (struct_name_variable struct_name) method_name1(input_paras...) [return_type] { /* 方法实现 */ } func (struct_name_variable struct_name) method_name2(input_paras...) [return_type] { /* 方法实现*/ } func (struct_name_variable struct_name) method_name3(input_paras...) [return_type] { /* 方法实现*/ }
go语言的源码中大量使用到了接口,比如说在前面的文章中多次使用到的 error 类型
// The error built-in interface type is the conventional interface for // representing an error condition, with the nil value representing no error. type error interface { Error() string }
封装性
接口是 golang 封装性的重要一环,接口可以封装具体类型和类型的值,即使一个类型还有别的方法,接口的实例也只能调用接口暴露出来的方法。如下:
type HelloInterface interface { Hello() } type User struct { } func (f *User) Hello() { fmt.Println("hello") } func (f *User) Bye() { fmt.Println("bye") } func InterfaceTest() { u := &User{} u.Hello() // ok u.Bye() // ok var user HelloInterface = new(User) // 接口实例化 user.Hello() // ok user.Bye() // Compile error: user.Bye undefined (type HelloInterface has no field or method Bye) }
注意,使用一个接口对象必须要先实例化,否则接口对象的值为 nil,调用 nil 对象的任何方法都会产生空指针 panic。
接口查询
和查询某个元素是否在 map 中类似,Golang 也内置了接口查询,可以使用和 map 类似的语法来检查对象实例是否实现了接口,如下:
var user HelloInterface = new(User) // 接口实例化 if u1, ok := user.(HelloInterface); ok { fmt.Println(u1) // yes } if u2, ok := user.(Reader); ok { fmt.Println(u2) // no }
也可以查询对象是否是某个类型
if u3, ok := user.(*User); ok { fmt.Println(u3) }
Golang 还可以使用断言和反射来进行类型查询,这两个内容会在后续的文章中介绍。
接口赋值
将对象实例赋值给接口
要将对象实例赋值给接口,要求该对象实例实现了接口要求的所有方法。如:
type Integer int func (a Integer) Less(b Integer) bool { return a < b } func (a *Integer) Add(b Integer) { *a += b } type LessAdder interface { Less(b Integer) bool Add(b Integer) } var a Integer = 1 var b LessAdder = &a
注意,此处赋值时用
&a
而不是a
, 因为 Go 会自动为 *Integer 生成一个新的 Less 方法func (a *Integer) Less(b Integer) bool { return (*a).Less(b) }
从而让 *Integer 既存在 Less(),又存在 Add(), 满足接口 LessAdder
将一个接口赋值给另一个接口
在Go语言中,只要两个接口拥有相同的方法列表(不用考虑顺序),那么它们就是等同的,可以相互赋值。
package one type ReadWriter1 interface { Read(buf []byte) (n int, err error) Write(buf []byte) (n int, err error) } // 第二个接口位于另一个包中: package two type ReadWriter2 interface { Write(buf []byte) (n int, err error) Read(buf []byte) (n int, err error) } // 可以相互赋值 var file1 two.ReadWriter2 = new(File) var file2 one.ReadWriter1 = file1 var file3 two.ReadWriter2 = file2
接口赋值并不要求两个接口必须等价。如果接口 A 的方法列表是接口 B 的方法列表的子集, 那么接口 B可以赋值给接口 A,但是 A 不可以赋值给 B。(大接口可以赋值给小接口)
接口组合
类似于结构内嵌,接口的组合也是使用匿名机制实现的,如下:
type Reader interface { Read(p []byte) (n int, err error) } type Writer interface { Write(p []byte) (n int, err error) } // 将 Read 和 Write 方法组合 // ReadWriter 接口既能做 Reader 接口的所有事情,又能做 Writer 接口的所有事情。 type ReadWriter interface { Reader Writer } // 与下面的写法完全等价 type ReadWriter interface { Read(p []byte) (n int, err error) Write(p []byte) (n int, err error) }
Any 类型
Go语言中任何对象实例都满足空接口
interface{}
,所以可以把interface{}
看作可以指向任何对象的Any
类型,当函数可以接受任意的对象实例时,我们会将其声明为interface{}
,从而可以接受任意类型的对象,然后再使用类型断言来对该参数进行转换,再做后续的处理(具体内容参看类型断言的博客)。最典型的例子是标准库
fmt
中 PrintXXX 系列的函数,例如:func Printf(fmt string, args ...interface{}) func Println(args ...interface{})
sort interface 示例
接下来,让我们通过介绍内置的 sort 包来加深一下对接口的理解,顺便了解一下这个常用包的使用。
Golang 的 sort 包中通过接口的方式内置了可以对任何类型的列表进行快排的功能,下面我们一起来看看它是如何使用的。
首先我们要先了解
sort.Interface
源码中定义了哪些方法:// A type, typically a collection, that satisfies sort.Interface can be // sorted by the routines in this package. The methods require that the // elements of the collection be enumerated by an integer index. type Interface interface { // Len is the number of elements in the collection. Len() int // Less reports whether the element with // index i should sort before the element with index j. Less(i, j int) bool // Swap swaps the elements with indexes i and j. Swap(i, j int) }
可以看到,我们需要先定义三个方法:
- 计算列表长度的方法
- 比较两个元素的方法
- 交换两个元素的方法
因此,我们需要定义一种类型,这种类型要同时具有以上三种方法,比如一个简单的 Student 类
type Student struct { ID int64 Name string } type StudentSlice []*Student func (s StudentSlice) Len() int { return len(s) } func (s StudentSlice) Less(i, j int) bool { return s[i].ID < s[j].ID } func (s StudentSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
接下来,对一个 Student 进行初始化
s1 := &Student{ ID: 1, Name: "A", } s2 := &Student{ ID: 2, Name: "B", } s3 := &Student{ ID: 3, Name: "C", } students := []*Student{s3, s1, s2}
准备工作已经做好,接下来我们先来看一下
sort.Sort
函数的源码// Sort sorts data. // It makes one call to data.Len to determine n, and O(n*log(n)) calls to // data.Less and data.Swap. The sort is not guaranteed to be stable. func Sort(data Interface) { n := data.Len() quickSort(data, 0, n, maxDepth(n)) }
可以看到,函数的入参是一个
sort.Interface
类型的对象,然后对这个对象进行快排操作,所以,要使用这个函数,我们还需要把[]*Student
类型转换成StudentSlice
,由于StudentSlice
实现了sort.Interface
的所有方法,所以StudentSlice
的对象就是sort.Interface
类型的对象。sort.Sort(StudentSlice(students))
完成后,打印 students,我们就可以看到排好序的列表了。
{ID:1 Name:A} {ID:2 Name:B} {ID:3 Name:C}
对于自定义的类型,要进行排序就要完成上述的所有操作,幸运的是,对于常用基本类型,go 源码已经为我们准备好了一系列可以直接调用的方法。
// Ints sorts a slice of ints in increasing order. func Ints(a []int) { Sort(IntSlice(a)) } // Float64s sorts a slice of float64s in increasing order // (not-a-number values are treated as less than other values). func Float64s(a []float64) { Sort(Float64Slice(a)) } // Strings sorts a slice of strings in increasing order. func Strings(a []string) { Sort(StringSlice(a)) } // IntsAreSorted tests whether a slice of ints is sorted in increasing order. func IntsAreSorted(a []int) bool { return IsSorted(IntSlice(a)) } // Float64sAreSorted tests whether a slice of float64s is sorted in increasing order // (not-a-number values are treated as less than other values). func Float64sAreSorted(a []float64) bool { return IsSorted(Float64Slice(a)) } // StringsAreSorted tests whether a slice of strings is sorted in increasing order. func StringsAreSorted(a []string) bool { return IsSorted(StringSlice(a)) }
我们可以直接使用这些方法对基本类型 slice 进行排序,如:
ids := []int{5,1,7,1,3,8,7,4} names := []string{"qqq", "www", "ee", "aa", "rr", "ba"} sort.Ints(ids) sort.Strings(names) fmt.Println(ids) // [1 1 3 4 5 7 7 8] fmt.Println(names) // [aa ba ee qqq rr www]
-
java中接口(interface)及使用方法和注意事项
2018-10-09 16:38:59在JAVA编程语言中是一个抽象类型,是抽象方法的集合,接口通常以interface来声明。一个类通过继承接口的方式,从而来继承接口的抽象方法。 接口并不是类,编写接口的方式和类很相似,但是它们属于不同... -
【Groovy】Groovy 方法调用 ( Java 中函数参数是接口类型 | 函数参数是接口类型 可以 直接传递闭包 )
2022-01-03 21:50:33完整代码示例 : interface OnClickListener { void onClick() } void setOnClickListener (OnClickListener onClickListener) { onClickListener.onClick() } // 正常参数调用 setOnClickListener(new ... -
C#中的接口interface的使用
2018-09-04 11:43:52interface类似于C++中的继承基类的虚函数,子类重写方法后。将调用对应子类的方法。 原文档https://blog.csdn.net/qq_36922335/article/details/73339342 接口是指定一组函数成员而不实现他们的引用类型。所以... -
Interface的两种使用方式
2016-05-25 19:59:47Interface的两种使用方式接口是我们在编程中经常使用的,原来对于使用方式一直模模糊糊的,这两天整理了一下。作为菜鸟,有不对的地方请多多指教,不喜勿喷。 通过set方法进行传递。例如Activity中去调用Fragment里... -
Kotlin -- 接口(Interface)
2018-03-01 23:20:36Kotlin – 接口(Interface) interface用于声明一个接口类: interface Speakable{ fun say() } 然后通过:来实现接口,顺带说一下,在kotlin中,:是一个很强大的符号,对应于Java的implements、extends都... -
一分钟带你搞清楚ts中 interface 和 type 的概念和用法(较全)
2021-09-03 17:07:10提示:刚学习TS 的新手看到type 和 interface 会分不清楚什么场景下怎么使用,所以写一篇文章总结一下 一、概念 type : 类型别名 概念:可以给一个或多个数据类型(string、number、…)取一个别名; 举例: type ... -
java interface有多个implement的情况下,@Inject调用实现类的选择
2015-08-25 16:13:49java interface有多个implement的情况下,@Inject调用实现类的选择 -
java native interface JNI 调用Java方法
2014-05-06 14:52:52在上一篇文章中介绍了JNI,以及java调用JNI,这篇讲一下 JNI调用java方法。 通过使用合适的JNI函数,你可以创建Java对象,get、set 静态(static)和 实例(instance)的域,调用静态(static)和实例(instance... -
C#调用Delphi接口(ITest = interface)
2016-05-27 18:57:39Delphi开发的导出Interface的DLL,使用C#调用的技术 -
PSR-11 Container interface:依赖注入容器的通用接口-开源
2021-07-12 16:26:12ContainerInterface 设定的目标是标准化框架和库如何使用容器来获取对象和参数。 条目标识符是至少一个字符的任何 PHP 合法字符串,用于唯一标识容器内的项目。 条目标识符是一个不透明的字符串,因此调用者不应假设... -
java接口的默认方法,实现类调用接口默认方法
2021-07-28 23:48:47概述 Java8带来了一些全新的特性,包括lambda表达式、函数接口、方法引用、流、可选方法、接口中的静态方法和默认方法。...public interface MyInterface { // 普通接口方法 default void defaultMethod -
入门学习Objective-C中的@interface与@implementation
2017-04-04 15:19:32这里嵌套调用了alloc和init两个方法,同init可以一直初始化到Car的父类,也就是NSObject类(Objective-C类中一切类的基类),而alloc则会自动管理内存,把关联的对象分配到一个相邻的内存区域内,以便于调用时消耗很... -
40、C#:如何调用外部dll的接口
2017-11-23 20:54:28如果要用别人dll中的接口,以此来调用别人的服务(别人的服务必须是开启的,而且要能通过expo服务调用到),应该如何做? 1.首先将别人的dll引用到自己的项目中来(添加引用即可) 2.然后将别人的接口添加到项目的... -
【Bug】同一接口多实现类下dubbo调用服务错乱
2019-02-21 21:42:30有两个项目A、B,各自有一定数量实现了CommonService接口的实现类,而当将这些实现类...dubbo:service interface=“com.xxx.CommonService” ref=“receiveService” /&gt; &lt;dubbo:service inter... -
PHP MySQL DatabaseInterface:PHP MySQL DatabaseInterface 是一个生成 MySQL 语句的工具。-开源
2021-08-03 13:21:08开发者只需要关心DatabaseInterface 对象的格式化参数和调用save、select 或delete 程序。 DatabaseInterface 将确保传递的参数经过清理,数据结构正确,并决定每次调用时要做什么(取决于调用的过程)。 数据库... -
java interface 接口 及 接口的调用 实例及误区
2017-08-26 16:17:58public interface Comparable_Define<T> { public int compareTo(T other); } /* 如果本文第二块代码块的首部改为 public class TestComparableInterface implements Comparable_Define 就不可以编译正确了 *... -
用 interface 作为参数来解决不同对象调用同样方法
2018-11-20 11:41:37今天遇到一个场景,将不同的方法对象,或是不同类型的对象,都要调用同一个方法,那么这个方法可以创建一个 interface 作为入参,然后让不同的对象都 implements 此方法,则可以解决此问题 For example--》 ... -
javascript interface 调用
2011-04-20 23:06:09<!... <head><title>javascript对象创建 <script type="text/javascript" src="../Interface/Interface.js"> var Person = new Interface('Person',['getName']);..." onclick="p1()">调用a标记 -
【JAVA】-调用链设计demo
2021-01-20 13:39:08【JAVA】-调用链设计demo1-JAVA链式调用1-1 执行链1-2 执行者1-3 程序调用者,执行链的主要实现1-4 程序调用者,执行链的主要实现 1-JAVA链式调用 1-1 执行链 主要作用是执行 public interface ExectorChain { void... -
领悟php接口中interface存在的意义
2020-12-19 14:38:52可能大家都懂这些,作为不懂的我猜测了一下这个interface的意义,他就是为了后面调用的时候再调用的方法中调用实现类中interface中存在的内容,好绕口啊,写个例子留作以后看吧pay.php复制代码 代码如下:interface ... -
Kotlin无法调用到Java中定义的interface类的问题记录
2018-11-21 14:45:25一个kotlin类,调用一个Java类中的一个方法。引发了下面这个错误。 因为我在kotlin中调用了了java代码中定义的一个接口,然后就报错一个IllegalAccessError错误。如下: E/AndroidRuntime: FATAL EXCEPTION: main ... -
14、Interface_SystemVerilog_20210728.pdf
2021-07-28 17:50:49初学者学习SystemVerilog——Interface最好的资料之一,全面讲解了interface的组成与调用方法,全部是作者自己通过对interface的理解以及应用的总结。 -
使用Java8的函数式接口@FunctionalInterface实现简单异步调用
2017-08-25 18:23:11最近研究了一下异步调用,接下来几篇博客是跟异步调用相关的,首先使用@FunctionalInterface接口实现一个简单的步调用,也就是本篇博客主要内容。 然后再加上ZMQ,实现一个带网络通信的异步调用。再下一步就是复杂... -
Go语言标准库学习之reflect——Go语言中如何通过反射获取interface{}类型数据的值、类型以及方法调用
2020-09-02 14:10:11一、interface和反射 1. Go语言中类型设计原则 学习反射前,我们先了解一下Golang关于类型设计的一些原则: 变量包括(type,value)两部分。 type包括static type和concrete type,简单来说static type是在编码看...